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 G_LOG_LEVEL_CRITICAL,
570 "%s: assertion `%s' failed",
575 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
577 (wc >= 0x80 && wc < 0xa0)))
580 strdup_convert (const gchar *string,
581 const gchar *charset)
583 if (!g_utf8_validate (string, -1, NULL))
585 GString *gstring = g_string_new ("[Invalid UTF-8] ");
588 for (p = (guchar *)string; *p; p++)
590 if (CHAR_IS_SAFE(*p) &&
591 !(*p == '\r' && *(p + 1) != '\n') &&
593 g_string_append_c (gstring, *p);
595 g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
598 return g_string_free (gstring, FALSE);
604 gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
609 /* Not thread-safe, but doesn't matter if we print the warning twice
611 static gboolean warned = FALSE;
615 ensure_stderr_valid ();
616 _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
620 return g_strdup (string);
625 /* For a radix of 8 we need at most 3 output bytes for 1 input
626 * byte. Additionally we might need up to 2 output bytes for the
627 * readix prefix and 1 byte for the trailing NULL.
629 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
632 format_unsigned (gchar *buf,
640 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
642 if (radix != 8 && radix != 10 && radix != 16)
675 /* Again we can't use g_assert; actually this check should _never_ fail. */
676 if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
689 buf[i] = c + 'a' - 10;
696 /* string size big enough to hold level prefix */
697 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
699 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
701 static GFileDescriptor
702 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
705 gboolean to_stdout = TRUE;
707 /* we may not call _any_ GLib functions here */
709 switch (log_level & G_LOG_LEVEL_MASK)
711 case G_LOG_LEVEL_ERROR:
712 strcpy (level_prefix, "ERROR");
715 case G_LOG_LEVEL_CRITICAL:
716 strcpy (level_prefix, "CRITICAL");
719 case G_LOG_LEVEL_WARNING:
720 strcpy (level_prefix, "WARNING");
723 case G_LOG_LEVEL_MESSAGE:
724 strcpy (level_prefix, "Message");
727 case G_LOG_LEVEL_INFO:
728 strcpy (level_prefix, "INFO");
730 case G_LOG_LEVEL_DEBUG:
731 strcpy (level_prefix, "DEBUG");
736 strcpy (level_prefix, "LOG-");
737 format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
740 strcpy (level_prefix, "LOG");
743 if (log_level & G_LOG_FLAG_RECURSION)
744 strcat (level_prefix, " (recursed)");
745 if (log_level & ALERT_LEVELS)
746 strcat (level_prefix, " **");
749 win32_keep_fatal_message = (log_level & G_LOG_FLAG_FATAL) != 0;
753 ensure_stdout_valid ();
758 ensure_stderr_valid ();
762 return to_stdout ? 1 : 2;
767 _g_log_fallback_handler (const gchar *log_domain,
768 GLogLevelFlags log_level,
769 const gchar *message,
770 gpointer unused_data)
772 gchar level_prefix[STRING_BUFFER_SIZE], pid_string[FORMAT_UNSIGNED_BUFSIZE];
773 gboolean is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
776 /* we can not call _any_ GLib functions in this fallback handler,
777 * which is why we skip UTF-8 conversion, etc.
778 * since we either recursed or ran out of memory, we're in a pretty
779 * pathologic situation anyways, what we can do is giving the
780 * the process ID unconditionally however.
783 fd = mklevel_prefix (level_prefix, log_level);
785 message = "(NULL) message";
787 format_unsigned (pid_string, getpid (), 10);
790 write_string (fd, "\n");
792 write_string (fd, "\n** ");
793 write_string (fd, "(process:");
794 write_string (fd, pid_string);
795 write_string (fd, "): ");
798 write_string (fd, log_domain);
799 write_string (fd, "-");
801 write_string (fd, level_prefix);
802 write_string (fd, ": ");
803 write_string (fd, message);
805 write_string (fd, "\naborting...\n");
807 write_string (fd, "\n");
811 escape_string (GString *string)
813 const char *p = string->str;
816 while (p < string->str + string->len)
820 wc = g_utf8_get_char_validated (p, -1);
821 if (wc == (gunichar)-1 || wc == (gunichar)-2)
826 pos = p - string->str;
828 /* Emit invalid UTF-8 as hex escapes
830 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
831 g_string_erase (string, pos, 1);
832 g_string_insert (string, pos, tmp);
834 p = string->str + (pos + 4); /* Skip over escape sequence */
841 safe = *(p + 1) == '\n';
845 safe = CHAR_IS_SAFE (wc);
853 pos = p - string->str;
855 /* Largest char we escape is 0x0a, so we don't have to worry
856 * about 8-digit \Uxxxxyyyy
858 tmp = g_strdup_printf ("\\u%04x", wc);
859 g_string_erase (string, pos, g_utf8_next_char (p) - p);
860 g_string_insert (string, pos, tmp);
863 p = string->str + (pos + 6); /* Skip over escape sequence */
866 p = g_utf8_next_char (p);
871 g_log_default_handler (const gchar *log_domain,
872 GLogLevelFlags log_level,
873 const gchar *message,
874 gpointer unused_data)
876 gboolean is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
877 gchar level_prefix[STRING_BUFFER_SIZE], *string;
881 /* we can be called externally with recursion for whatever reason */
882 if (log_level & G_LOG_FLAG_RECURSION)
884 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
888 g_messages_prefixed_init ();
890 fd = mklevel_prefix (level_prefix, log_level);
892 gstring = g_string_new (NULL);
893 if (log_level & ALERT_LEVELS)
894 g_string_append (gstring, "\n");
896 g_string_append (gstring, "** ");
898 if ((g_log_msg_prefix & log_level) == log_level)
900 const gchar *prg_name = g_get_prgname ();
903 g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
905 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
910 g_string_append (gstring, log_domain);
911 g_string_append_c (gstring, '-');
913 g_string_append (gstring, level_prefix);
915 g_string_append (gstring, ": ");
917 g_string_append (gstring, "(NULL) message");
921 const gchar *charset;
923 msg = g_string_new (message);
926 if (g_get_charset (&charset))
927 g_string_append (gstring, msg->str); /* charset is UTF-8 already */
930 string = strdup_convert (msg->str, charset);
931 g_string_append (gstring, string);
935 g_string_free (msg, TRUE);
938 g_string_append (gstring, "\naborting...\n");
940 g_string_append (gstring, "\n");
942 string = g_string_free (gstring, FALSE);
944 write_string (fd, string);
949 g_set_print_handler (GPrintFunc func)
951 GPrintFunc old_print_func;
953 g_mutex_lock (g_messages_lock);
954 old_print_func = glib_print_func;
955 glib_print_func = func;
956 g_mutex_unlock (g_messages_lock);
958 return old_print_func;
962 g_print (const gchar *format,
967 GPrintFunc local_glib_print_func;
969 g_return_if_fail (format != NULL);
971 va_start (args, format);
972 string = g_strdup_vprintf (format, args);
975 g_mutex_lock (g_messages_lock);
976 local_glib_print_func = glib_print_func;
977 g_mutex_unlock (g_messages_lock);
979 if (local_glib_print_func)
980 local_glib_print_func (string);
983 const gchar *charset;
985 ensure_stdout_valid ();
986 if (g_get_charset (&charset))
987 fputs (string, stdout); /* charset is UTF-8 already */
990 gchar *lstring = strdup_convert (string, charset);
992 fputs (lstring, stdout);
1001 g_set_printerr_handler (GPrintFunc func)
1003 GPrintFunc old_printerr_func;
1005 g_mutex_lock (g_messages_lock);
1006 old_printerr_func = glib_printerr_func;
1007 glib_printerr_func = func;
1008 g_mutex_unlock (g_messages_lock);
1010 return old_printerr_func;
1014 g_printerr (const gchar *format,
1019 GPrintFunc local_glib_printerr_func;
1021 g_return_if_fail (format != NULL);
1023 va_start (args, format);
1024 string = g_strdup_vprintf (format, args);
1027 g_mutex_lock (g_messages_lock);
1028 local_glib_printerr_func = glib_printerr_func;
1029 g_mutex_unlock (g_messages_lock);
1031 if (local_glib_printerr_func)
1032 local_glib_printerr_func (string);
1035 const gchar *charset;
1037 ensure_stderr_valid ();
1038 if (g_get_charset (&charset))
1039 fputs (string, stderr); /* charset is UTF-8 already */
1042 gchar *lstring = strdup_convert (string, charset);
1044 fputs (lstring, stderr);
1053 g_printf_string_upper_bound (const gchar *format,
1057 return _g_vsnprintf (&c, 1, format, args) + 1;
1061 _g_messages_thread_init (void)
1063 g_messages_lock = g_mutex_new ();
1064 g_messages_prefixed_init ();
1069 _g_messages_thread_private_init (void)
1071 g_assert (g_log_depth == NULL);
1072 g_log_depth = g_private_new (NULL);
1075 gboolean _g_debug_initialized = FALSE;
1076 guint _g_debug_flags = 0;
1079 _g_debug_init (void)
1083 _g_debug_initialized = TRUE;
1085 val = g_getenv ("G_DEBUG");
1088 static const GDebugKey keys[] = {
1089 {"fatal_warnings", G_DEBUG_FATAL_WARNINGS}
1092 _g_debug_flags = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
1095 if (_g_debug_flags & G_DEBUG_FATAL_WARNINGS)
1097 GLogLevelFlags fatal_mask;
1099 fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
1100 fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
1101 g_log_set_always_fatal (fatal_mask);