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/.
47 #include "gprintfint.h"
48 #include "gthreadinit.h"
52 typedef FILE* GFileDescriptor;
54 typedef gint GFileDescriptor;
57 /* --- structures --- */
58 typedef struct _GLogDomain GLogDomain;
59 typedef struct _GLogHandler GLogHandler;
63 GLogLevelFlags fatal_mask;
64 GLogHandler *handlers;
70 GLogLevelFlags log_level;
77 /* --- variables --- */
78 static GMutex *g_messages_lock = NULL;
79 static GLogDomain *g_log_domains = NULL;
80 static GLogLevelFlags g_log_always_fatal = G_LOG_FATAL_MASK;
81 static GPrintFunc glib_print_func = NULL;
82 static GPrintFunc glib_printerr_func = NULL;
83 static GPrivate *g_log_depth = NULL;
84 static GLogLevelFlags g_log_msg_prefix = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_DEBUG;
85 static GLogFunc default_log_func = g_log_default_handler;
86 static gpointer default_log_data = NULL;
88 /* --- functions --- */
93 # include <process.h> /* For _getpid() */
94 static gboolean win32_keep_fatal_message = FALSE;
96 /* This default message will usually be overwritten. */
97 /* Yes, a fixed size buffer is bad. So sue me. But g_error is never
98 * with huge strings, is it?
100 static gchar fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
101 static gchar *fatal_msg_ptr = fatal_msg_buf;
103 /* Just use stdio. If we're out of memory, we're hosed anyway. */
106 dowrite (GFileDescriptor fd,
110 if (win32_keep_fatal_message)
112 memcpy (fatal_msg_ptr, buf, len);
113 fatal_msg_ptr += len;
118 fwrite (buf, len, 1, fd);
123 #define write(fd, buf, len) dowrite(fd, buf, len)
126 ensure_stdout_valid (void)
128 static gboolean alloc_console_called = FALSE;
131 if (win32_keep_fatal_message)
134 if (!alloc_console_called)
136 handle = (HANDLE) _get_osfhandle (fileno (stdout));
138 if (handle == INVALID_HANDLE_VALUE)
141 alloc_console_called = TRUE;
142 freopen ("CONOUT$", "w", stdout);
148 ensure_stderr_valid (void)
150 static gboolean alloc_console_called = FALSE;
153 if (win32_keep_fatal_message)
156 if (!alloc_console_called)
158 handle = (HANDLE) _get_osfhandle (fileno (stderr));
160 if (handle == INVALID_HANDLE_VALUE)
163 alloc_console_called = TRUE;
164 freopen ("CONOUT$", "w", stderr);
170 #define ensure_stdout_valid() /* Define as empty */
171 #define ensure_stderr_valid()
175 write_string (GFileDescriptor fd,
178 write (fd, string, strlen (string));
182 g_messages_prefixed_init (void)
184 static gboolean initialized = FALSE;
191 val = g_getenv ("G_MESSAGES_PREFIXED");
195 static const GDebugKey keys[] = {
196 { "error", G_LOG_LEVEL_ERROR },
197 { "critical", G_LOG_LEVEL_CRITICAL },
198 { "warning", G_LOG_LEVEL_WARNING },
199 { "message", G_LOG_LEVEL_MESSAGE },
200 { "info", G_LOG_LEVEL_INFO },
201 { "debug", G_LOG_LEVEL_DEBUG }
204 g_log_msg_prefix = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
210 g_log_find_domain_L (const gchar *log_domain)
212 register GLogDomain *domain;
214 domain = g_log_domains;
217 if (strcmp (domain->log_domain, log_domain) == 0)
219 domain = domain->next;
225 g_log_domain_new_L (const gchar *log_domain)
227 register GLogDomain *domain;
229 domain = g_new (GLogDomain, 1);
230 domain->log_domain = g_strdup (log_domain);
231 domain->fatal_mask = G_LOG_FATAL_MASK;
232 domain->handlers = NULL;
234 domain->next = g_log_domains;
235 g_log_domains = domain;
241 g_log_domain_check_free_L (GLogDomain *domain)
243 if (domain->fatal_mask == G_LOG_FATAL_MASK &&
244 domain->handlers == NULL)
246 register GLogDomain *last, *work;
250 work = g_log_domains;
256 last->next = domain->next;
258 g_log_domains = domain->next;
259 g_free (domain->log_domain);
270 g_log_domain_get_handler_L (GLogDomain *domain,
271 GLogLevelFlags log_level,
274 if (domain && log_level)
276 register GLogHandler *handler;
278 handler = domain->handlers;
281 if ((handler->log_level & log_level) == log_level)
283 *data = handler->data;
284 return handler->log_func;
286 handler = handler->next;
290 *data = default_log_data;
291 return default_log_func;
295 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
297 GLogLevelFlags old_mask;
299 /* restrict the global mask to levels that are known to glib
300 * since this setting applies to all domains
302 fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
303 /* force errors to be fatal */
304 fatal_mask |= G_LOG_LEVEL_ERROR;
305 /* remove bogus flag */
306 fatal_mask &= ~G_LOG_FLAG_FATAL;
308 g_mutex_lock (g_messages_lock);
309 old_mask = g_log_always_fatal;
310 g_log_always_fatal = fatal_mask;
311 g_mutex_unlock (g_messages_lock);
317 g_log_set_fatal_mask (const gchar *log_domain,
318 GLogLevelFlags fatal_mask)
320 GLogLevelFlags old_flags;
321 register GLogDomain *domain;
326 /* force errors to be fatal */
327 fatal_mask |= G_LOG_LEVEL_ERROR;
328 /* remove bogus flag */
329 fatal_mask &= ~G_LOG_FLAG_FATAL;
331 g_mutex_lock (g_messages_lock);
333 domain = g_log_find_domain_L (log_domain);
335 domain = g_log_domain_new_L (log_domain);
336 old_flags = domain->fatal_mask;
338 domain->fatal_mask = fatal_mask;
339 g_log_domain_check_free_L (domain);
341 g_mutex_unlock (g_messages_lock);
347 g_log_set_handler (const gchar *log_domain,
348 GLogLevelFlags log_levels,
352 static guint handler_id = 0;
354 GLogHandler *handler;
356 g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
357 g_return_val_if_fail (log_func != NULL, 0);
362 handler = g_new (GLogHandler, 1);
364 g_mutex_lock (g_messages_lock);
366 domain = g_log_find_domain_L (log_domain);
368 domain = g_log_domain_new_L (log_domain);
370 handler->id = ++handler_id;
371 handler->log_level = log_levels;
372 handler->log_func = log_func;
373 handler->data = user_data;
374 handler->next = domain->handlers;
375 domain->handlers = handler;
377 g_mutex_unlock (g_messages_lock);
383 g_log_set_default_handler (GLogFunc log_func,
386 GLogFunc old_log_func;
388 g_mutex_lock (g_messages_lock);
389 old_log_func = default_log_func;
390 default_log_func = log_func;
391 default_log_data = user_data;
392 g_mutex_unlock (g_messages_lock);
398 g_log_remove_handler (const gchar *log_domain,
401 register GLogDomain *domain;
403 g_return_if_fail (handler_id > 0);
408 g_mutex_lock (g_messages_lock);
409 domain = g_log_find_domain_L (log_domain);
412 GLogHandler *work, *last;
415 work = domain->handlers;
418 if (work->id == handler_id)
421 last->next = work->next;
423 domain->handlers = work->next;
424 g_log_domain_check_free_L (domain);
425 g_mutex_unlock (g_messages_lock);
433 g_mutex_unlock (g_messages_lock);
434 g_warning ("%s: could not find handler with id `%d' for domain \"%s\"",
435 G_STRLOC, handler_id, log_domain);
439 g_logv (const gchar *log_domain,
440 GLogLevelFlags log_level,
444 gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
445 gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
448 log_level &= G_LOG_LEVEL_MASK;
452 for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
454 register GLogLevelFlags test_level;
457 if (log_level & test_level)
459 guint depth = GPOINTER_TO_UINT (g_private_get (g_log_depth));
462 guint domain_fatal_mask;
463 gpointer data = NULL;
466 test_level |= G_LOG_FLAG_FATAL;
468 test_level |= G_LOG_FLAG_RECURSION;
470 /* check recursion and lookup handler */
471 g_mutex_lock (g_messages_lock);
472 domain = g_log_find_domain_L (log_domain ? log_domain : "");
474 test_level |= G_LOG_FLAG_RECURSION;
476 domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
477 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
478 test_level |= G_LOG_FLAG_FATAL;
479 if (test_level & G_LOG_FLAG_RECURSION)
480 log_func = _g_log_fallback_handler;
482 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
484 g_mutex_unlock (g_messages_lock);
486 g_private_set (g_log_depth, GUINT_TO_POINTER (depth));
488 /* had to defer debug initialization until we can keep track of recursion */
489 if (!(test_level & G_LOG_FLAG_RECURSION) && !_g_debug_initialized)
491 guint orig_test_level = test_level;
494 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
495 test_level |= G_LOG_FLAG_FATAL;
496 if (test_level != orig_test_level)
498 /* need a relookup, not nice, but not too bad either */
499 g_mutex_lock (g_messages_lock);
500 domain = g_log_find_domain_L (log_domain ? log_domain : "");
501 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
503 g_mutex_unlock (g_messages_lock);
507 if (test_level & G_LOG_FLAG_RECURSION)
509 /* we use a stack buffer of fixed size, since we're likely
510 * in an out-of-memory situation
514 size = _g_vsnprintf (buffer, 1024, format, args1);
516 log_func (log_domain, test_level, buffer, data);
520 gchar *msg = g_strdup_vprintf (format, args1);
522 log_func (log_domain, test_level, msg, data);
527 if (test_level & G_LOG_FLAG_FATAL)
530 gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
532 MessageBox (NULL, locale_msg, NULL,
533 MB_ICONERROR|MB_SETFOREGROUND);
535 #if defined (G_ENABLE_DEBUG) && (defined (SIGTRAP) || defined (G_OS_WIN32))
536 if (!(test_level & G_LOG_FLAG_RECURSION))
540 #else /* !G_ENABLE_DEBUG || !(SIGTRAP || G_OS_WIN32) */
542 #endif /* !G_ENABLE_DEBUG || !(SIGTRAP || G_OS_WIN32) */
546 g_private_set (g_log_depth, GUINT_TO_POINTER (depth));
552 g_log (const gchar *log_domain,
553 GLogLevelFlags log_level,
559 va_start (args, format);
560 g_logv (log_domain, log_level, format, args);
565 g_return_if_fail_warning (const char *log_domain,
566 const char *pretty_function,
567 const char *expression)
570 * Omit the prefix used by the PLT-reduction
571 * technique used in GTK+.
573 if (g_str_has_prefix (pretty_function, "IA__"))
574 pretty_function += 4;
576 G_LOG_LEVEL_CRITICAL,
577 "%s: assertion `%s' failed",
582 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
584 (wc >= 0x80 && wc < 0xa0)))
587 strdup_convert (const gchar *string,
588 const gchar *charset)
590 if (!g_utf8_validate (string, -1, NULL))
592 GString *gstring = g_string_new ("[Invalid UTF-8] ");
595 for (p = (guchar *)string; *p; p++)
597 if (CHAR_IS_SAFE(*p) &&
598 !(*p == '\r' && *(p + 1) != '\n') &&
600 g_string_append_c (gstring, *p);
602 g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
605 return g_string_free (gstring, FALSE);
611 gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
616 /* Not thread-safe, but doesn't matter if we print the warning twice
618 static gboolean warned = FALSE;
622 ensure_stderr_valid ();
623 _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
627 return g_strdup (string);
632 /* For a radix of 8 we need at most 3 output bytes for 1 input
633 * byte. Additionally we might need up to 2 output bytes for the
634 * readix prefix and 1 byte for the trailing NULL.
636 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
639 format_unsigned (gchar *buf,
647 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
649 if (radix != 8 && radix != 10 && radix != 16)
682 /* Again we can't use g_assert; actually this check should _never_ fail. */
683 if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
696 buf[i] = c + 'a' - 10;
703 /* string size big enough to hold level prefix */
704 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
706 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
708 static GFileDescriptor
709 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
712 gboolean to_stdout = TRUE;
714 /* we may not call _any_ GLib functions here */
716 switch (log_level & G_LOG_LEVEL_MASK)
718 case G_LOG_LEVEL_ERROR:
719 strcpy (level_prefix, "ERROR");
722 case G_LOG_LEVEL_CRITICAL:
723 strcpy (level_prefix, "CRITICAL");
726 case G_LOG_LEVEL_WARNING:
727 strcpy (level_prefix, "WARNING");
730 case G_LOG_LEVEL_MESSAGE:
731 strcpy (level_prefix, "Message");
734 case G_LOG_LEVEL_INFO:
735 strcpy (level_prefix, "INFO");
737 case G_LOG_LEVEL_DEBUG:
738 strcpy (level_prefix, "DEBUG");
743 strcpy (level_prefix, "LOG-");
744 format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
747 strcpy (level_prefix, "LOG");
750 if (log_level & G_LOG_FLAG_RECURSION)
751 strcat (level_prefix, " (recursed)");
752 if (log_level & ALERT_LEVELS)
753 strcat (level_prefix, " **");
756 win32_keep_fatal_message = (log_level & G_LOG_FLAG_FATAL) != 0;
760 ensure_stdout_valid ();
765 ensure_stderr_valid ();
769 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], pid_string[FORMAT_UNSIGNED_BUFSIZE];
780 gboolean is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
783 /* we can not call _any_ GLib functions in this fallback handler,
784 * which is why we skip UTF-8 conversion, etc.
785 * since we either recursed or ran out of memory, we're in a pretty
786 * pathologic situation anyways, what we can do is giving the
787 * the process ID unconditionally however.
790 fd = mklevel_prefix (level_prefix, log_level);
792 message = "(NULL) message";
794 format_unsigned (pid_string, getpid (), 10);
797 write_string (fd, "\n");
799 write_string (fd, "\n** ");
800 write_string (fd, "(process:");
801 write_string (fd, pid_string);
802 write_string (fd, "): ");
805 write_string (fd, log_domain);
806 write_string (fd, "-");
808 write_string (fd, level_prefix);
809 write_string (fd, ": ");
810 write_string (fd, message);
812 write_string (fd, "\naborting...\n");
814 write_string (fd, "\n");
818 escape_string (GString *string)
820 const char *p = string->str;
823 while (p < string->str + string->len)
827 wc = g_utf8_get_char_validated (p, -1);
828 if (wc == (gunichar)-1 || wc == (gunichar)-2)
833 pos = p - string->str;
835 /* Emit invalid UTF-8 as hex escapes
837 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
838 g_string_erase (string, pos, 1);
839 g_string_insert (string, pos, tmp);
841 p = string->str + (pos + 4); /* Skip over escape sequence */
848 safe = *(p + 1) == '\n';
852 safe = CHAR_IS_SAFE (wc);
860 pos = p - string->str;
862 /* Largest char we escape is 0x0a, so we don't have to worry
863 * about 8-digit \Uxxxxyyyy
865 tmp = g_strdup_printf ("\\u%04x", wc);
866 g_string_erase (string, pos, g_utf8_next_char (p) - p);
867 g_string_insert (string, pos, tmp);
870 p = string->str + (pos + 6); /* Skip over escape sequence */
873 p = g_utf8_next_char (p);
878 g_log_default_handler (const gchar *log_domain,
879 GLogLevelFlags log_level,
880 const gchar *message,
881 gpointer unused_data)
883 gboolean is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
884 gchar level_prefix[STRING_BUFFER_SIZE], *string;
888 /* we can be called externally with recursion for whatever reason */
889 if (log_level & G_LOG_FLAG_RECURSION)
891 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
895 g_messages_prefixed_init ();
897 fd = mklevel_prefix (level_prefix, log_level);
899 gstring = g_string_new (NULL);
900 if (log_level & ALERT_LEVELS)
901 g_string_append (gstring, "\n");
903 g_string_append (gstring, "** ");
905 if ((g_log_msg_prefix & log_level) == log_level)
907 const gchar *prg_name = g_get_prgname ();
910 g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
912 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
917 g_string_append (gstring, log_domain);
918 g_string_append_c (gstring, '-');
920 g_string_append (gstring, level_prefix);
922 g_string_append (gstring, ": ");
924 g_string_append (gstring, "(NULL) message");
928 const gchar *charset;
930 msg = g_string_new (message);
933 if (g_get_charset (&charset))
934 g_string_append (gstring, msg->str); /* charset is UTF-8 already */
937 string = strdup_convert (msg->str, charset);
938 g_string_append (gstring, string);
942 g_string_free (msg, TRUE);
945 g_string_append (gstring, "\naborting...\n");
947 g_string_append (gstring, "\n");
949 string = g_string_free (gstring, FALSE);
951 write_string (fd, string);
956 g_set_print_handler (GPrintFunc func)
958 GPrintFunc old_print_func;
960 g_mutex_lock (g_messages_lock);
961 old_print_func = glib_print_func;
962 glib_print_func = func;
963 g_mutex_unlock (g_messages_lock);
965 return old_print_func;
969 g_print (const gchar *format,
974 GPrintFunc local_glib_print_func;
976 g_return_if_fail (format != NULL);
978 va_start (args, format);
979 string = g_strdup_vprintf (format, args);
982 g_mutex_lock (g_messages_lock);
983 local_glib_print_func = glib_print_func;
984 g_mutex_unlock (g_messages_lock);
986 if (local_glib_print_func)
987 local_glib_print_func (string);
990 const gchar *charset;
992 ensure_stdout_valid ();
993 if (g_get_charset (&charset))
994 fputs (string, stdout); /* charset is UTF-8 already */
997 gchar *lstring = strdup_convert (string, charset);
999 fputs (lstring, stdout);
1008 g_set_printerr_handler (GPrintFunc func)
1010 GPrintFunc old_printerr_func;
1012 g_mutex_lock (g_messages_lock);
1013 old_printerr_func = glib_printerr_func;
1014 glib_printerr_func = func;
1015 g_mutex_unlock (g_messages_lock);
1017 return old_printerr_func;
1021 g_printerr (const gchar *format,
1026 GPrintFunc local_glib_printerr_func;
1028 g_return_if_fail (format != NULL);
1030 va_start (args, format);
1031 string = g_strdup_vprintf (format, args);
1034 g_mutex_lock (g_messages_lock);
1035 local_glib_printerr_func = glib_printerr_func;
1036 g_mutex_unlock (g_messages_lock);
1038 if (local_glib_printerr_func)
1039 local_glib_printerr_func (string);
1042 const gchar *charset;
1044 ensure_stderr_valid ();
1045 if (g_get_charset (&charset))
1046 fputs (string, stderr); /* charset is UTF-8 already */
1049 gchar *lstring = strdup_convert (string, charset);
1051 fputs (lstring, stderr);
1060 g_printf_string_upper_bound (const gchar *format,
1064 return _g_vsnprintf (&c, 1, format, args) + 1;
1068 _g_messages_thread_init (void)
1070 g_messages_lock = g_mutex_new ();
1071 g_messages_prefixed_init ();
1076 _g_messages_thread_private_init (void)
1078 g_assert (g_log_depth == NULL);
1079 g_log_depth = g_private_new (NULL);
1082 gboolean _g_debug_initialized = FALSE;
1083 guint _g_debug_flags = 0;
1086 _g_debug_init (void)
1090 _g_debug_initialized = TRUE;
1092 val = g_getenv ("G_DEBUG");
1095 static const GDebugKey keys[] = {
1096 {"fatal_warnings", G_DEBUG_FATAL_WARNINGS}
1099 _g_debug_flags = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
1102 if (_g_debug_flags & G_DEBUG_FATAL_WARNINGS)
1104 GLogLevelFlags fatal_mask;
1106 fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
1107 fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
1108 g_log_set_always_fatal (fatal_mask);