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/.
46 #include "gprintfint.h"
47 #include "gthreadinit.h"
51 typedef FILE* GFileDescriptor;
53 typedef gint GFileDescriptor;
56 /* --- structures --- */
57 typedef struct _GLogDomain GLogDomain;
58 typedef struct _GLogHandler GLogHandler;
62 GLogLevelFlags fatal_mask;
63 GLogHandler *handlers;
69 GLogLevelFlags log_level;
76 /* --- variables --- */
77 static GMutex *g_messages_lock = NULL;
78 static GLogDomain *g_log_domains = NULL;
79 static GLogLevelFlags g_log_always_fatal = G_LOG_FATAL_MASK;
80 static GPrintFunc glib_print_func = NULL;
81 static GPrintFunc glib_printerr_func = NULL;
82 static GPrivate *g_log_depth = NULL;
83 static GLogLevelFlags g_log_msg_prefix = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_DEBUG;
84 static GLogFunc default_log_func = g_log_default_handler;
85 static gpointer default_log_data = NULL;
87 /* --- functions --- */
92 # include <process.h> /* For _getpid() */
93 static gboolean win32_keep_fatal_message = FALSE;
95 /* This default message will usually be overwritten. */
96 /* Yes, a fixed size buffer is bad. So sue me. But g_error is never
97 * with huge strings, is it?
99 static gchar fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
100 static gchar *fatal_msg_ptr = fatal_msg_buf;
102 /* Just use stdio. If we're out of memory, we're hosed anyway. */
105 dowrite (GFileDescriptor fd,
109 if (win32_keep_fatal_message)
111 memcpy (fatal_msg_ptr, buf, len);
112 fatal_msg_ptr += len;
117 fwrite (buf, len, 1, fd);
122 #define write(fd, buf, len) dowrite(fd, buf, len)
125 ensure_stdout_valid (void)
127 static gboolean alloc_console_called = FALSE;
130 if (win32_keep_fatal_message)
133 if (!alloc_console_called)
135 handle = (HANDLE) _get_osfhandle (fileno (stdout));
137 if (handle == INVALID_HANDLE_VALUE)
140 alloc_console_called = TRUE;
141 freopen ("CONOUT$", "w", stdout);
147 ensure_stderr_valid (void)
149 static gboolean alloc_console_called = FALSE;
152 if (win32_keep_fatal_message)
155 if (!alloc_console_called)
157 handle = (HANDLE) _get_osfhandle (fileno (stderr));
159 if (handle == INVALID_HANDLE_VALUE)
162 alloc_console_called = TRUE;
163 freopen ("CONOUT$", "w", stderr);
169 #define ensure_stdout_valid() /* Define as empty */
170 #define ensure_stderr_valid()
174 write_string (GFileDescriptor fd,
177 write (fd, string, strlen (string));
181 g_messages_prefixed_init (void)
183 static gboolean initialized = FALSE;
190 val = g_getenv ("G_MESSAGES_PREFIXED");
194 static const GDebugKey keys[] = {
195 { "error", G_LOG_LEVEL_ERROR },
196 { "critical", G_LOG_LEVEL_CRITICAL },
197 { "warning", G_LOG_LEVEL_WARNING },
198 { "message", G_LOG_LEVEL_MESSAGE },
199 { "info", G_LOG_LEVEL_INFO },
200 { "debug", G_LOG_LEVEL_DEBUG }
203 g_log_msg_prefix = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
209 g_log_find_domain_L (const gchar *log_domain)
211 register GLogDomain *domain;
213 domain = g_log_domains;
216 if (strcmp (domain->log_domain, log_domain) == 0)
218 domain = domain->next;
224 g_log_domain_new_L (const gchar *log_domain)
226 register GLogDomain *domain;
228 domain = g_new (GLogDomain, 1);
229 domain->log_domain = g_strdup (log_domain);
230 domain->fatal_mask = G_LOG_FATAL_MASK;
231 domain->handlers = NULL;
233 domain->next = g_log_domains;
234 g_log_domains = domain;
240 g_log_domain_check_free_L (GLogDomain *domain)
242 if (domain->fatal_mask == G_LOG_FATAL_MASK &&
243 domain->handlers == NULL)
245 register GLogDomain *last, *work;
249 work = g_log_domains;
255 last->next = domain->next;
257 g_log_domains = domain->next;
258 g_free (domain->log_domain);
269 g_log_domain_get_handler_L (GLogDomain *domain,
270 GLogLevelFlags log_level,
273 if (domain && log_level)
275 register GLogHandler *handler;
277 handler = domain->handlers;
280 if ((handler->log_level & log_level) == log_level)
282 *data = handler->data;
283 return handler->log_func;
285 handler = handler->next;
289 *data = default_log_data;
290 return default_log_func;
294 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
296 GLogLevelFlags old_mask;
298 /* restrict the global mask to levels that are known to glib
299 * since this setting applies to all domains
301 fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
302 /* force errors to be fatal */
303 fatal_mask |= G_LOG_LEVEL_ERROR;
304 /* remove bogus flag */
305 fatal_mask &= ~G_LOG_FLAG_FATAL;
307 g_mutex_lock (g_messages_lock);
308 old_mask = g_log_always_fatal;
309 g_log_always_fatal = fatal_mask;
310 g_mutex_unlock (g_messages_lock);
316 g_log_set_fatal_mask (const gchar *log_domain,
317 GLogLevelFlags fatal_mask)
319 GLogLevelFlags old_flags;
320 register GLogDomain *domain;
325 /* force errors to be fatal */
326 fatal_mask |= G_LOG_LEVEL_ERROR;
327 /* remove bogus flag */
328 fatal_mask &= ~G_LOG_FLAG_FATAL;
330 g_mutex_lock (g_messages_lock);
332 domain = g_log_find_domain_L (log_domain);
334 domain = g_log_domain_new_L (log_domain);
335 old_flags = domain->fatal_mask;
337 domain->fatal_mask = fatal_mask;
338 g_log_domain_check_free_L (domain);
340 g_mutex_unlock (g_messages_lock);
346 g_log_set_handler (const gchar *log_domain,
347 GLogLevelFlags log_levels,
351 static guint handler_id = 0;
353 GLogHandler *handler;
355 g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
356 g_return_val_if_fail (log_func != NULL, 0);
361 handler = g_new (GLogHandler, 1);
363 g_mutex_lock (g_messages_lock);
365 domain = g_log_find_domain_L (log_domain);
367 domain = g_log_domain_new_L (log_domain);
369 handler->id = ++handler_id;
370 handler->log_level = log_levels;
371 handler->log_func = log_func;
372 handler->data = user_data;
373 handler->next = domain->handlers;
374 domain->handlers = handler;
376 g_mutex_unlock (g_messages_lock);
382 g_log_set_default_handler (GLogFunc log_func,
385 GLogFunc old_log_func;
387 g_mutex_lock (g_messages_lock);
388 old_log_func = default_log_func;
389 default_log_func = log_func;
390 default_log_data = user_data;
391 g_mutex_unlock (g_messages_lock);
397 g_log_remove_handler (const gchar *log_domain,
400 register GLogDomain *domain;
402 g_return_if_fail (handler_id > 0);
407 g_mutex_lock (g_messages_lock);
408 domain = g_log_find_domain_L (log_domain);
411 GLogHandler *work, *last;
414 work = domain->handlers;
417 if (work->id == handler_id)
420 last->next = work->next;
422 domain->handlers = work->next;
423 g_log_domain_check_free_L (domain);
424 g_mutex_unlock (g_messages_lock);
432 g_mutex_unlock (g_messages_lock);
433 g_warning ("%s: could not find handler with id `%d' for domain \"%s\"",
434 G_STRLOC, handler_id, log_domain);
438 g_logv (const gchar *log_domain,
439 GLogLevelFlags log_level,
443 gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
444 gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
447 log_level &= G_LOG_LEVEL_MASK;
451 for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
453 register GLogLevelFlags test_level;
456 if (log_level & test_level)
458 guint depth = GPOINTER_TO_UINT (g_private_get (g_log_depth));
461 guint domain_fatal_mask;
462 gpointer data = NULL;
465 test_level |= G_LOG_FLAG_FATAL;
467 test_level |= G_LOG_FLAG_RECURSION;
469 /* check recursion and lookup handler */
470 g_mutex_lock (g_messages_lock);
471 domain = g_log_find_domain_L (log_domain ? log_domain : "");
473 test_level |= G_LOG_FLAG_RECURSION;
475 domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
476 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
477 test_level |= G_LOG_FLAG_FATAL;
478 if (test_level & G_LOG_FLAG_RECURSION)
479 log_func = _g_log_fallback_handler;
481 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
483 g_mutex_unlock (g_messages_lock);
485 g_private_set (g_log_depth, GUINT_TO_POINTER (depth));
487 /* had to defer debug initialization until we can keep track of recursion */
488 if (!(test_level & G_LOG_FLAG_RECURSION) && !_g_debug_initialized)
490 guint orig_test_level = test_level;
493 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
494 test_level |= G_LOG_FLAG_FATAL;
495 if (test_level != orig_test_level)
497 /* need a relookup, not nice, but not too bad either */
498 g_mutex_lock (g_messages_lock);
499 domain = g_log_find_domain_L (log_domain ? log_domain : "");
500 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
502 g_mutex_unlock (g_messages_lock);
506 if (test_level & G_LOG_FLAG_RECURSION)
508 /* we use a stack buffer of fixed size, since we're likely
509 * in an out-of-memory situation
513 size = _g_vsnprintf (buffer, 1024, format, args1);
515 log_func (log_domain, test_level, buffer, data);
519 gchar *msg = g_strdup_vprintf (format, args1);
521 log_func (log_domain, test_level, msg, data);
526 if (test_level & G_LOG_FLAG_FATAL)
529 gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
531 MessageBox (NULL, locale_msg, NULL,
532 MB_ICONERROR|MB_SETFOREGROUND);
534 #if defined (G_ENABLE_DEBUG) && (defined (SIGTRAP) || defined (G_OS_WIN32))
535 if (!(test_level & G_LOG_FLAG_RECURSION))
539 #else /* !G_ENABLE_DEBUG || !(SIGTRAP || G_OS_WIN32) */
541 #endif /* !G_ENABLE_DEBUG || !(SIGTRAP || G_OS_WIN32) */
545 g_private_set (g_log_depth, GUINT_TO_POINTER (depth));
551 g_log (const gchar *log_domain,
552 GLogLevelFlags log_level,
558 va_start (args, format);
559 g_logv (log_domain, log_level, format, args);
564 g_return_if_fail_warning (const char *log_domain,
565 const char *pretty_function,
566 const char *expression)
569 * Omit the prefix used by the PLT-reduction
570 * technique used in GTK+.
572 if (g_str_has_prefix (pretty_function, "IA__"))
573 pretty_function += 4;
575 G_LOG_LEVEL_CRITICAL,
576 "%s: assertion `%s' failed",
581 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
583 (wc >= 0x80 && wc < 0xa0)))
586 strdup_convert (const gchar *string,
587 const gchar *charset)
589 if (!g_utf8_validate (string, -1, NULL))
591 GString *gstring = g_string_new ("[Invalid UTF-8] ");
594 for (p = (guchar *)string; *p; p++)
596 if (CHAR_IS_SAFE(*p) &&
597 !(*p == '\r' && *(p + 1) != '\n') &&
599 g_string_append_c (gstring, *p);
601 g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
604 return g_string_free (gstring, FALSE);
610 gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
615 /* Not thread-safe, but doesn't matter if we print the warning twice
617 static gboolean warned = FALSE;
621 ensure_stderr_valid ();
622 _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
626 return g_strdup (string);
631 /* For a radix of 8 we need at most 3 output bytes for 1 input
632 * byte. Additionally we might need up to 2 output bytes for the
633 * readix prefix and 1 byte for the trailing NULL.
635 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
638 format_unsigned (gchar *buf,
646 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
648 if (radix != 8 && radix != 10 && radix != 16)
681 /* Again we can't use g_assert; actually this check should _never_ fail. */
682 if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
695 buf[i] = c + 'a' - 10;
702 /* string size big enough to hold level prefix */
703 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
705 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
707 static GFileDescriptor
708 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
711 gboolean to_stdout = TRUE;
713 /* we may not call _any_ GLib functions here */
715 switch (log_level & G_LOG_LEVEL_MASK)
717 case G_LOG_LEVEL_ERROR:
718 strcpy (level_prefix, "ERROR");
721 case G_LOG_LEVEL_CRITICAL:
722 strcpy (level_prefix, "CRITICAL");
725 case G_LOG_LEVEL_WARNING:
726 strcpy (level_prefix, "WARNING");
729 case G_LOG_LEVEL_MESSAGE:
730 strcpy (level_prefix, "Message");
733 case G_LOG_LEVEL_INFO:
734 strcpy (level_prefix, "INFO");
736 case G_LOG_LEVEL_DEBUG:
737 strcpy (level_prefix, "DEBUG");
742 strcpy (level_prefix, "LOG-");
743 format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
746 strcpy (level_prefix, "LOG");
749 if (log_level & G_LOG_FLAG_RECURSION)
750 strcat (level_prefix, " (recursed)");
751 if (log_level & ALERT_LEVELS)
752 strcat (level_prefix, " **");
755 win32_keep_fatal_message = (log_level & G_LOG_FLAG_FATAL) != 0;
759 ensure_stdout_valid ();
764 ensure_stderr_valid ();
768 return to_stdout ? 1 : 2;
773 _g_log_fallback_handler (const gchar *log_domain,
774 GLogLevelFlags log_level,
775 const gchar *message,
776 gpointer unused_data)
778 gchar level_prefix[STRING_BUFFER_SIZE], pid_string[FORMAT_UNSIGNED_BUFSIZE];
779 gboolean is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
782 /* we can not call _any_ GLib functions in this fallback handler,
783 * which is why we skip UTF-8 conversion, etc.
784 * since we either recursed or ran out of memory, we're in a pretty
785 * pathologic situation anyways, what we can do is giving the
786 * the process ID unconditionally however.
789 fd = mklevel_prefix (level_prefix, log_level);
791 message = "(NULL) message";
793 format_unsigned (pid_string, getpid (), 10);
796 write_string (fd, "\n");
798 write_string (fd, "\n** ");
799 write_string (fd, "(process:");
800 write_string (fd, pid_string);
801 write_string (fd, "): ");
804 write_string (fd, log_domain);
805 write_string (fd, "-");
807 write_string (fd, level_prefix);
808 write_string (fd, ": ");
809 write_string (fd, message);
811 write_string (fd, "\naborting...\n");
813 write_string (fd, "\n");
817 escape_string (GString *string)
819 const char *p = string->str;
822 while (p < string->str + string->len)
826 wc = g_utf8_get_char_validated (p, -1);
827 if (wc == (gunichar)-1 || wc == (gunichar)-2)
832 pos = p - string->str;
834 /* Emit invalid UTF-8 as hex escapes
836 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
837 g_string_erase (string, pos, 1);
838 g_string_insert (string, pos, tmp);
840 p = string->str + (pos + 4); /* Skip over escape sequence */
847 safe = *(p + 1) == '\n';
851 safe = CHAR_IS_SAFE (wc);
859 pos = p - string->str;
861 /* Largest char we escape is 0x0a, so we don't have to worry
862 * about 8-digit \Uxxxxyyyy
864 tmp = g_strdup_printf ("\\u%04x", wc);
865 g_string_erase (string, pos, g_utf8_next_char (p) - p);
866 g_string_insert (string, pos, tmp);
869 p = string->str + (pos + 6); /* Skip over escape sequence */
872 p = g_utf8_next_char (p);
877 g_log_default_handler (const gchar *log_domain,
878 GLogLevelFlags log_level,
879 const gchar *message,
880 gpointer unused_data)
882 gboolean is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
883 gchar level_prefix[STRING_BUFFER_SIZE], *string;
887 /* we can be called externally with recursion for whatever reason */
888 if (log_level & G_LOG_FLAG_RECURSION)
890 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
894 g_messages_prefixed_init ();
896 fd = mklevel_prefix (level_prefix, log_level);
898 gstring = g_string_new (NULL);
899 if (log_level & ALERT_LEVELS)
900 g_string_append (gstring, "\n");
902 g_string_append (gstring, "** ");
904 if ((g_log_msg_prefix & log_level) == log_level)
906 const gchar *prg_name = g_get_prgname ();
909 g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
911 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
916 g_string_append (gstring, log_domain);
917 g_string_append_c (gstring, '-');
919 g_string_append (gstring, level_prefix);
921 g_string_append (gstring, ": ");
923 g_string_append (gstring, "(NULL) message");
927 const gchar *charset;
929 msg = g_string_new (message);
932 if (g_get_charset (&charset))
933 g_string_append (gstring, msg->str); /* charset is UTF-8 already */
936 string = strdup_convert (msg->str, charset);
937 g_string_append (gstring, string);
941 g_string_free (msg, TRUE);
944 g_string_append (gstring, "\naborting...\n");
946 g_string_append (gstring, "\n");
948 string = g_string_free (gstring, FALSE);
950 write_string (fd, string);
955 g_set_print_handler (GPrintFunc func)
957 GPrintFunc old_print_func;
959 g_mutex_lock (g_messages_lock);
960 old_print_func = glib_print_func;
961 glib_print_func = func;
962 g_mutex_unlock (g_messages_lock);
964 return old_print_func;
968 g_print (const gchar *format,
973 GPrintFunc local_glib_print_func;
975 g_return_if_fail (format != NULL);
977 va_start (args, format);
978 string = g_strdup_vprintf (format, args);
981 g_mutex_lock (g_messages_lock);
982 local_glib_print_func = glib_print_func;
983 g_mutex_unlock (g_messages_lock);
985 if (local_glib_print_func)
986 local_glib_print_func (string);
989 const gchar *charset;
991 ensure_stdout_valid ();
992 if (g_get_charset (&charset))
993 fputs (string, stdout); /* charset is UTF-8 already */
996 gchar *lstring = strdup_convert (string, charset);
998 fputs (lstring, stdout);
1007 g_set_printerr_handler (GPrintFunc func)
1009 GPrintFunc old_printerr_func;
1011 g_mutex_lock (g_messages_lock);
1012 old_printerr_func = glib_printerr_func;
1013 glib_printerr_func = func;
1014 g_mutex_unlock (g_messages_lock);
1016 return old_printerr_func;
1020 g_printerr (const gchar *format,
1025 GPrintFunc local_glib_printerr_func;
1027 g_return_if_fail (format != NULL);
1029 va_start (args, format);
1030 string = g_strdup_vprintf (format, args);
1033 g_mutex_lock (g_messages_lock);
1034 local_glib_printerr_func = glib_printerr_func;
1035 g_mutex_unlock (g_messages_lock);
1037 if (local_glib_printerr_func)
1038 local_glib_printerr_func (string);
1041 const gchar *charset;
1043 ensure_stderr_valid ();
1044 if (g_get_charset (&charset))
1045 fputs (string, stderr); /* charset is UTF-8 already */
1048 gchar *lstring = strdup_convert (string, charset);
1050 fputs (lstring, stderr);
1059 g_printf_string_upper_bound (const gchar *format,
1063 return _g_vsnprintf (&c, 1, format, args) + 1;
1067 _g_messages_thread_init (void)
1069 g_messages_lock = g_mutex_new ();
1070 g_messages_prefixed_init ();
1075 _g_messages_thread_private_init (void)
1077 g_assert (g_log_depth == NULL);
1078 g_log_depth = g_private_new (NULL);
1081 gboolean _g_debug_initialized = FALSE;
1082 guint _g_debug_flags = 0;
1085 _g_debug_init (void)
1089 _g_debug_initialized = TRUE;
1091 val = g_getenv ("G_DEBUG");
1094 static const GDebugKey keys[] = {
1095 {"fatal_warnings", G_DEBUG_FATAL_WARNINGS}
1098 _g_debug_flags = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
1101 if (_g_debug_flags & G_DEBUG_FATAL_WARNINGS)
1103 GLogLevelFlags fatal_mask;
1105 fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
1106 fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
1107 g_log_set_always_fatal (fatal_mask);