Updated British English translation
[glib.git] / glib / gmessages.c
blob986087567226d8ec6b33d356ec0944f141d5647d
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/.
28 * MT safe
31 /**
32 * SECTION:warnings
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.
49 #include "config.h"
51 #include <stdlib.h>
52 #include <stdarg.h>
53 #include <stdio.h>
54 #include <string.h>
55 #ifdef HAVE_UNISTD_H
56 #include <unistd.h>
57 #endif
58 #include <signal.h>
59 #include <locale.h>
60 #include <errno.h>
62 #include "gmessages.h"
64 #include "gbacktrace.h"
65 #include "gconvert.h"
66 #include "gdebug.h"
67 #include "gmem.h"
68 #include "gprintfint.h"
69 #include "gtestutils.h"
70 #include "gthread.h"
71 #include "gthreadprivate.h"
72 #include "gstrfuncs.h"
73 #include "gstring.h"
75 #ifdef G_OS_WIN32
76 #include <process.h> /* For getpid() */
77 #include <io.h>
78 # define STRICT /* Strict typing, please */
79 # define _WIN32_WINDOWS 0x0401 /* to get IsDebuggerPresent */
80 # include <windows.h>
81 # undef STRICT
82 #endif
85 /* --- structures --- */
86 typedef struct _GLogDomain GLogDomain;
87 typedef struct _GLogHandler GLogHandler;
88 struct _GLogDomain
90 gchar *log_domain;
91 GLogLevelFlags fatal_mask;
92 GLogHandler *handlers;
93 GLogDomain *next;
95 struct _GLogHandler
97 guint id;
98 GLogLevelFlags log_level;
99 GLogFunc log_func;
100 gpointer data;
101 GLogHandler *next;
105 /* --- variables --- */
106 static GMutex *g_messages_lock = NULL;
107 static GLogDomain *g_log_domains = NULL;
108 static GLogLevelFlags g_log_always_fatal = G_LOG_FATAL_MASK;
109 static GPrintFunc glib_print_func = NULL;
110 static GPrintFunc glib_printerr_func = NULL;
111 static GPrivate *g_log_depth = NULL;
112 static GLogLevelFlags g_log_msg_prefix = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_DEBUG;
113 static GLogFunc default_log_func = g_log_default_handler;
114 static gpointer default_log_data = NULL;
115 static GTestLogFatalFunc fatal_log_func = NULL;
116 static gpointer fatal_log_data;
118 /* --- functions --- */
119 #ifdef G_OS_WIN32
120 # define STRICT
121 # include <windows.h>
122 # undef STRICT
123 static gboolean win32_keep_fatal_message = FALSE;
125 /* This default message will usually be overwritten. */
126 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
127 * called with huge strings, is it?
129 static gchar fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
130 static gchar *fatal_msg_ptr = fatal_msg_buf;
132 #undef write
133 static inline int
134 dowrite (int fd,
135 const void *buf,
136 unsigned int len)
138 if (win32_keep_fatal_message)
140 memcpy (fatal_msg_ptr, buf, len);
141 fatal_msg_ptr += len;
142 *fatal_msg_ptr = 0;
143 return len;
146 write (fd, buf, len);
148 return len;
150 #define write(fd, buf, len) dowrite(fd, buf, len)
152 #endif
154 static void
155 write_string (int fd,
156 const gchar *string)
158 write (fd, string, strlen (string));
161 static void
162 g_messages_prefixed_init (void)
164 static gboolean initialized = FALSE;
166 if (!initialized)
168 const gchar *val;
170 initialized = TRUE;
171 val = g_getenv ("G_MESSAGES_PREFIXED");
173 if (val)
175 const GDebugKey keys[] = {
176 { "error", G_LOG_LEVEL_ERROR },
177 { "critical", G_LOG_LEVEL_CRITICAL },
178 { "warning", G_LOG_LEVEL_WARNING },
179 { "message", G_LOG_LEVEL_MESSAGE },
180 { "info", G_LOG_LEVEL_INFO },
181 { "debug", G_LOG_LEVEL_DEBUG }
184 g_log_msg_prefix = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
189 static GLogDomain*
190 g_log_find_domain_L (const gchar *log_domain)
192 register GLogDomain *domain;
194 domain = g_log_domains;
195 while (domain)
197 if (strcmp (domain->log_domain, log_domain) == 0)
198 return domain;
199 domain = domain->next;
201 return NULL;
204 static GLogDomain*
205 g_log_domain_new_L (const gchar *log_domain)
207 register GLogDomain *domain;
209 domain = g_new (GLogDomain, 1);
210 domain->log_domain = g_strdup (log_domain);
211 domain->fatal_mask = G_LOG_FATAL_MASK;
212 domain->handlers = NULL;
214 domain->next = g_log_domains;
215 g_log_domains = domain;
217 return domain;
220 static void
221 g_log_domain_check_free_L (GLogDomain *domain)
223 if (domain->fatal_mask == G_LOG_FATAL_MASK &&
224 domain->handlers == NULL)
226 register GLogDomain *last, *work;
228 last = NULL;
230 work = g_log_domains;
231 while (work)
233 if (work == domain)
235 if (last)
236 last->next = domain->next;
237 else
238 g_log_domains = domain->next;
239 g_free (domain->log_domain);
240 g_free (domain);
241 break;
243 last = work;
244 work = last->next;
249 static GLogFunc
250 g_log_domain_get_handler_L (GLogDomain *domain,
251 GLogLevelFlags log_level,
252 gpointer *data)
254 if (domain && log_level)
256 register GLogHandler *handler;
258 handler = domain->handlers;
259 while (handler)
261 if ((handler->log_level & log_level) == log_level)
263 *data = handler->data;
264 return handler->log_func;
266 handler = handler->next;
270 *data = default_log_data;
271 return default_log_func;
274 GLogLevelFlags
275 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
277 GLogLevelFlags old_mask;
279 /* restrict the global mask to levels that are known to glib
280 * since this setting applies to all domains
282 fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
283 /* force errors to be fatal */
284 fatal_mask |= G_LOG_LEVEL_ERROR;
285 /* remove bogus flag */
286 fatal_mask &= ~G_LOG_FLAG_FATAL;
288 g_mutex_lock (g_messages_lock);
289 old_mask = g_log_always_fatal;
290 g_log_always_fatal = fatal_mask;
291 g_mutex_unlock (g_messages_lock);
293 return old_mask;
296 GLogLevelFlags
297 g_log_set_fatal_mask (const gchar *log_domain,
298 GLogLevelFlags fatal_mask)
300 GLogLevelFlags old_flags;
301 register GLogDomain *domain;
303 if (!log_domain)
304 log_domain = "";
306 /* force errors to be fatal */
307 fatal_mask |= G_LOG_LEVEL_ERROR;
308 /* remove bogus flag */
309 fatal_mask &= ~G_LOG_FLAG_FATAL;
311 g_mutex_lock (g_messages_lock);
313 domain = g_log_find_domain_L (log_domain);
314 if (!domain)
315 domain = g_log_domain_new_L (log_domain);
316 old_flags = domain->fatal_mask;
318 domain->fatal_mask = fatal_mask;
319 g_log_domain_check_free_L (domain);
321 g_mutex_unlock (g_messages_lock);
323 return old_flags;
326 guint
327 g_log_set_handler (const gchar *log_domain,
328 GLogLevelFlags log_levels,
329 GLogFunc log_func,
330 gpointer user_data)
332 static guint handler_id = 0;
333 GLogDomain *domain;
334 GLogHandler *handler;
336 g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
337 g_return_val_if_fail (log_func != NULL, 0);
339 if (!log_domain)
340 log_domain = "";
342 handler = g_new (GLogHandler, 1);
344 g_mutex_lock (g_messages_lock);
346 domain = g_log_find_domain_L (log_domain);
347 if (!domain)
348 domain = g_log_domain_new_L (log_domain);
350 handler->id = ++handler_id;
351 handler->log_level = log_levels;
352 handler->log_func = log_func;
353 handler->data = user_data;
354 handler->next = domain->handlers;
355 domain->handlers = handler;
357 g_mutex_unlock (g_messages_lock);
359 return handler_id;
362 GLogFunc
363 g_log_set_default_handler (GLogFunc log_func,
364 gpointer user_data)
366 GLogFunc old_log_func;
368 g_mutex_lock (g_messages_lock);
369 old_log_func = default_log_func;
370 default_log_func = log_func;
371 default_log_data = user_data;
372 g_mutex_unlock (g_messages_lock);
374 return old_log_func;
378 * g_test_log_set_fatal_handler:
379 * @log_func: the log handler function.
380 * @user_data: data passed to the log handler.
382 * Installs a non-error fatal log handler which can be
383 * used to decide whether log messages which are counted
384 * as fatal abort the program.
386 * The use case here is that you are running a test case
387 * that depends on particular libraries or circumstances
388 * and cannot prevent certain known critical or warning
389 * messages. So you install a handler that compares the
390 * domain and message to precisely not abort in such a case.
392 * Note that the handler is reset at the beginning of
393 * any test case, so you have to set it inside each test
394 * function which needs the special behavior.
396 * This handler has no effect on g_error messages.
398 * Since: 2.22
400 void
401 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
402 gpointer user_data)
404 g_mutex_lock (g_messages_lock);
405 fatal_log_func = log_func;
406 fatal_log_data = user_data;
407 g_mutex_unlock (g_messages_lock);
410 void
411 g_log_remove_handler (const gchar *log_domain,
412 guint handler_id)
414 register GLogDomain *domain;
416 g_return_if_fail (handler_id > 0);
418 if (!log_domain)
419 log_domain = "";
421 g_mutex_lock (g_messages_lock);
422 domain = g_log_find_domain_L (log_domain);
423 if (domain)
425 GLogHandler *work, *last;
427 last = NULL;
428 work = domain->handlers;
429 while (work)
431 if (work->id == handler_id)
433 if (last)
434 last->next = work->next;
435 else
436 domain->handlers = work->next;
437 g_log_domain_check_free_L (domain);
438 g_mutex_unlock (g_messages_lock);
439 g_free (work);
440 return;
442 last = work;
443 work = last->next;
446 g_mutex_unlock (g_messages_lock);
447 g_warning ("%s: could not find handler with id `%d' for domain \"%s\"",
448 G_STRLOC, handler_id, log_domain);
451 void
452 g_logv (const gchar *log_domain,
453 GLogLevelFlags log_level,
454 const gchar *format,
455 va_list args1)
457 gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
458 gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
459 gint i;
461 log_level &= G_LOG_LEVEL_MASK;
462 if (!log_level)
463 return;
465 for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
467 register GLogLevelFlags test_level;
469 test_level = 1 << i;
470 if (log_level & test_level)
472 guint depth = GPOINTER_TO_UINT (g_private_get (g_log_depth));
473 GLogDomain *domain;
474 GLogFunc log_func;
475 GLogLevelFlags domain_fatal_mask;
476 gpointer data = NULL;
477 gboolean masquerade_fatal = FALSE;
479 if (was_fatal)
480 test_level |= G_LOG_FLAG_FATAL;
481 if (was_recursion)
482 test_level |= G_LOG_FLAG_RECURSION;
484 /* check recursion and lookup handler */
485 g_mutex_lock (g_messages_lock);
486 domain = g_log_find_domain_L (log_domain ? log_domain : "");
487 if (depth)
488 test_level |= G_LOG_FLAG_RECURSION;
489 depth++;
490 domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
491 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
492 test_level |= G_LOG_FLAG_FATAL;
493 if (test_level & G_LOG_FLAG_RECURSION)
494 log_func = _g_log_fallback_handler;
495 else
496 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
497 domain = NULL;
498 g_mutex_unlock (g_messages_lock);
500 g_private_set (g_log_depth, GUINT_TO_POINTER (depth));
502 /* had to defer debug initialization until we can keep track of recursion */
503 if (!(test_level & G_LOG_FLAG_RECURSION) && !_g_debug_initialized)
505 GLogLevelFlags orig_test_level = test_level;
507 _g_debug_init ();
508 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
509 test_level |= G_LOG_FLAG_FATAL;
510 if (test_level != orig_test_level)
512 /* need a relookup, not nice, but not too bad either */
513 g_mutex_lock (g_messages_lock);
514 domain = g_log_find_domain_L (log_domain ? log_domain : "");
515 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
516 domain = NULL;
517 g_mutex_unlock (g_messages_lock);
521 if (test_level & G_LOG_FLAG_RECURSION)
523 /* we use a stack buffer of fixed size, since we're likely
524 * in an out-of-memory situation
526 gchar buffer[1025];
527 gsize size G_GNUC_UNUSED;
528 va_list args2;
530 G_VA_COPY (args2, args1);
531 size = _g_vsnprintf (buffer, 1024, format, args2);
532 va_end (args2);
534 log_func (log_domain, test_level, buffer, data);
536 else
538 gchar *msg;
539 va_list args2;
541 G_VA_COPY (args2, args1);
542 msg = g_strdup_vprintf (format, args2);
543 va_end (args2);
545 log_func (log_domain, test_level, msg, data);
547 if ((test_level & G_LOG_FLAG_FATAL)
548 && !(test_level & G_LOG_LEVEL_ERROR))
550 masquerade_fatal = fatal_log_func
551 && !fatal_log_func (log_domain, test_level, msg, data);
554 g_free (msg);
557 if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
559 #ifdef G_OS_WIN32
560 gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
562 MessageBox (NULL, locale_msg, NULL,
563 MB_ICONERROR|MB_SETFOREGROUND);
564 if (IsDebuggerPresent () && !(test_level & G_LOG_FLAG_RECURSION))
565 G_BREAKPOINT ();
566 else
567 abort ();
568 #else
569 if (!(test_level & G_LOG_FLAG_RECURSION))
570 G_BREAKPOINT ();
571 else
572 abort ();
573 #endif /* !G_OS_WIN32 */
576 depth--;
577 g_private_set (g_log_depth, GUINT_TO_POINTER (depth));
582 void
583 g_log (const gchar *log_domain,
584 GLogLevelFlags log_level,
585 const gchar *format,
586 ...)
588 va_list args;
590 va_start (args, format);
591 g_logv (log_domain, log_level, format, args);
592 va_end (args);
595 void
596 g_return_if_fail_warning (const char *log_domain,
597 const char *pretty_function,
598 const char *expression)
600 g_log (log_domain,
601 G_LOG_LEVEL_CRITICAL,
602 "%s: assertion `%s' failed",
603 pretty_function,
604 expression);
607 void
608 g_warn_message (const char *domain,
609 const char *file,
610 int line,
611 const char *func,
612 const char *warnexpr)
614 char *s, lstr[32];
615 g_snprintf (lstr, 32, "%d", line);
616 if (warnexpr)
617 s = g_strconcat ("(", file, ":", lstr, "):",
618 func, func[0] ? ":" : "",
619 " runtime check failed: (", warnexpr, ")", NULL);
620 else
621 s = g_strconcat ("(", file, ":", lstr, "):",
622 func, func[0] ? ":" : "",
623 " ", "code should not be reached", NULL);
624 g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
625 g_free (s);
628 void
629 g_assert_warning (const char *log_domain,
630 const char *file,
631 const int line,
632 const char *pretty_function,
633 const char *expression)
635 g_log (log_domain,
636 G_LOG_LEVEL_ERROR,
637 expression
638 ? "file %s: line %d (%s): assertion failed: (%s)"
639 : "file %s: line %d (%s): should not be reached",
640 file,
641 line,
642 pretty_function,
643 expression);
644 abort ();
647 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
648 (wc == 0x7f) || \
649 (wc >= 0x80 && wc < 0xa0)))
651 static gchar*
652 strdup_convert (const gchar *string,
653 const gchar *charset)
655 if (!g_utf8_validate (string, -1, NULL))
657 GString *gstring = g_string_new ("[Invalid UTF-8] ");
658 guchar *p;
660 for (p = (guchar *)string; *p; p++)
662 if (CHAR_IS_SAFE(*p) &&
663 !(*p == '\r' && *(p + 1) != '\n') &&
664 *p < 0x80)
665 g_string_append_c (gstring, *p);
666 else
667 g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
670 return g_string_free (gstring, FALSE);
672 else
674 GError *err = NULL;
676 gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
677 if (result)
678 return result;
679 else
681 /* Not thread-safe, but doesn't matter if we print the warning twice
683 static gboolean warned = FALSE;
684 if (!warned)
686 warned = TRUE;
687 _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
689 g_error_free (err);
691 return g_strdup (string);
696 /* For a radix of 8 we need at most 3 output bytes for 1 input
697 * byte. Additionally we might need up to 2 output bytes for the
698 * readix prefix and 1 byte for the trailing NULL.
700 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
702 static void
703 format_unsigned (gchar *buf,
704 gulong num,
705 guint radix)
707 gulong tmp;
708 gchar c;
709 gint i, n;
711 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
713 if (radix != 8 && radix != 10 && radix != 16)
715 *buf = '\000';
716 return;
719 if (!num)
721 *buf++ = '0';
722 *buf = '\000';
723 return;
726 if (radix == 16)
728 *buf++ = '0';
729 *buf++ = 'x';
731 else if (radix == 8)
733 *buf++ = '0';
736 n = 0;
737 tmp = num;
738 while (tmp)
740 tmp /= radix;
741 n++;
744 i = n;
746 /* Again we can't use g_assert; actually this check should _never_ fail. */
747 if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
749 *buf = '\000';
750 return;
753 while (num)
755 i--;
756 c = (num % radix);
757 if (c < 10)
758 buf[i] = c + '0';
759 else
760 buf[i] = c + 'a' - 10;
761 num /= radix;
764 buf[n] = '\000';
767 /* string size big enough to hold level prefix */
768 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
770 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
772 static int
773 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
774 GLogLevelFlags log_level)
776 gboolean to_stdout = TRUE;
778 /* we may not call _any_ GLib functions here */
780 switch (log_level & G_LOG_LEVEL_MASK)
782 case G_LOG_LEVEL_ERROR:
783 strcpy (level_prefix, "ERROR");
784 to_stdout = FALSE;
785 break;
786 case G_LOG_LEVEL_CRITICAL:
787 strcpy (level_prefix, "CRITICAL");
788 to_stdout = FALSE;
789 break;
790 case G_LOG_LEVEL_WARNING:
791 strcpy (level_prefix, "WARNING");
792 to_stdout = FALSE;
793 break;
794 case G_LOG_LEVEL_MESSAGE:
795 strcpy (level_prefix, "Message");
796 to_stdout = FALSE;
797 break;
798 case G_LOG_LEVEL_INFO:
799 strcpy (level_prefix, "INFO");
800 break;
801 case G_LOG_LEVEL_DEBUG:
802 strcpy (level_prefix, "DEBUG");
803 break;
804 default:
805 if (log_level)
807 strcpy (level_prefix, "LOG-");
808 format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
810 else
811 strcpy (level_prefix, "LOG");
812 break;
814 if (log_level & G_LOG_FLAG_RECURSION)
815 strcat (level_prefix, " (recursed)");
816 if (log_level & ALERT_LEVELS)
817 strcat (level_prefix, " **");
819 #ifdef G_OS_WIN32
820 win32_keep_fatal_message = (log_level & G_LOG_FLAG_FATAL) != 0;
821 #endif
822 return to_stdout ? 1 : 2;
825 void
826 _g_log_fallback_handler (const gchar *log_domain,
827 GLogLevelFlags log_level,
828 const gchar *message,
829 gpointer unused_data)
831 gchar level_prefix[STRING_BUFFER_SIZE];
832 #ifndef G_OS_WIN32
833 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
834 #endif
835 int fd;
837 /* we cannot call _any_ GLib functions in this fallback handler,
838 * which is why we skip UTF-8 conversion, etc.
839 * since we either recursed or ran out of memory, we're in a pretty
840 * pathologic situation anyways, what we can do is giving the
841 * the process ID unconditionally however.
844 fd = mklevel_prefix (level_prefix, log_level);
845 if (!message)
846 message = "(NULL) message";
848 #ifndef G_OS_WIN32
849 format_unsigned (pid_string, getpid (), 10);
850 #endif
852 if (log_domain)
853 write_string (fd, "\n");
854 else
855 write_string (fd, "\n** ");
857 #ifndef G_OS_WIN32
858 write_string (fd, "(process:");
859 write_string (fd, pid_string);
860 write_string (fd, "): ");
861 #endif
863 if (log_domain)
865 write_string (fd, log_domain);
866 write_string (fd, "-");
868 write_string (fd, level_prefix);
869 write_string (fd, ": ");
870 write_string (fd, message);
873 static void
874 escape_string (GString *string)
876 const char *p = string->str;
877 gunichar wc;
879 while (p < string->str + string->len)
881 gboolean safe;
883 wc = g_utf8_get_char_validated (p, -1);
884 if (wc == (gunichar)-1 || wc == (gunichar)-2)
886 gchar *tmp;
887 guint pos;
889 pos = p - string->str;
891 /* Emit invalid UTF-8 as hex escapes
893 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
894 g_string_erase (string, pos, 1);
895 g_string_insert (string, pos, tmp);
897 p = string->str + (pos + 4); /* Skip over escape sequence */
899 g_free (tmp);
900 continue;
902 if (wc == '\r')
904 safe = *(p + 1) == '\n';
906 else
908 safe = CHAR_IS_SAFE (wc);
911 if (!safe)
913 gchar *tmp;
914 guint pos;
916 pos = p - string->str;
918 /* Largest char we escape is 0x0a, so we don't have to worry
919 * about 8-digit \Uxxxxyyyy
921 tmp = g_strdup_printf ("\\u%04x", wc);
922 g_string_erase (string, pos, g_utf8_next_char (p) - p);
923 g_string_insert (string, pos, tmp);
924 g_free (tmp);
926 p = string->str + (pos + 6); /* Skip over escape sequence */
928 else
929 p = g_utf8_next_char (p);
933 void
934 g_log_default_handler (const gchar *log_domain,
935 GLogLevelFlags log_level,
936 const gchar *message,
937 gpointer unused_data)
939 gchar level_prefix[STRING_BUFFER_SIZE], *string;
940 GString *gstring;
941 int fd;
943 /* we can be called externally with recursion for whatever reason */
944 if (log_level & G_LOG_FLAG_RECURSION)
946 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
947 return;
950 g_messages_prefixed_init ();
952 fd = mklevel_prefix (level_prefix, log_level);
954 gstring = g_string_new (NULL);
955 if (log_level & ALERT_LEVELS)
956 g_string_append (gstring, "\n");
957 if (!log_domain)
958 g_string_append (gstring, "** ");
960 if ((g_log_msg_prefix & log_level) == log_level)
962 const gchar *prg_name = g_get_prgname ();
964 if (!prg_name)
965 g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
966 else
967 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
970 if (log_domain)
972 g_string_append (gstring, log_domain);
973 g_string_append_c (gstring, '-');
975 g_string_append (gstring, level_prefix);
977 g_string_append (gstring, ": ");
978 if (!message)
979 g_string_append (gstring, "(NULL) message");
980 else
982 GString *msg;
983 const gchar *charset;
985 msg = g_string_new (message);
986 escape_string (msg);
988 if (g_get_charset (&charset))
989 g_string_append (gstring, msg->str); /* charset is UTF-8 already */
990 else
992 string = strdup_convert (msg->str, charset);
993 g_string_append (gstring, string);
994 g_free (string);
997 g_string_free (msg, TRUE);
999 g_string_append (gstring, "\n");
1001 string = g_string_free (gstring, FALSE);
1003 write_string (fd, string);
1004 g_free (string);
1008 * g_set_print_handler:
1009 * @func: the new print handler
1011 * Sets the print handler.
1013 * Any messages passed to g_print() will be output via
1014 * the new handler. The default handler simply outputs
1015 * the message to stdout. By providing your own handler
1016 * you can redirect the output, to a GTK+ widget or a
1017 * log file for example.
1019 * Returns: the old print handler
1021 GPrintFunc
1022 g_set_print_handler (GPrintFunc func)
1024 GPrintFunc old_print_func;
1026 g_mutex_lock (g_messages_lock);
1027 old_print_func = glib_print_func;
1028 glib_print_func = func;
1029 g_mutex_unlock (g_messages_lock);
1031 return old_print_func;
1035 * g_print:
1036 * @format: the message format. See the printf() documentation
1037 * @...: the parameters to insert into the format string
1039 * Outputs a formatted message via the print handler.
1040 * The default print handler simply outputs the message to stdout.
1042 * g_print() should not be used from within libraries for debugging
1043 * messages, since it may be redirected by applications to special
1044 * purpose message windows or even files. Instead, libraries should
1045 * use g_log(), or the convenience functions g_message(), g_warning()
1046 * and g_error().
1048 void
1049 g_print (const gchar *format,
1050 ...)
1052 va_list args;
1053 gchar *string;
1054 GPrintFunc local_glib_print_func;
1056 g_return_if_fail (format != NULL);
1058 va_start (args, format);
1059 string = g_strdup_vprintf (format, args);
1060 va_end (args);
1062 g_mutex_lock (g_messages_lock);
1063 local_glib_print_func = glib_print_func;
1064 g_mutex_unlock (g_messages_lock);
1066 if (local_glib_print_func)
1067 local_glib_print_func (string);
1068 else
1070 const gchar *charset;
1072 if (g_get_charset (&charset))
1073 fputs (string, stdout); /* charset is UTF-8 already */
1074 else
1076 gchar *lstring = strdup_convert (string, charset);
1078 fputs (lstring, stdout);
1079 g_free (lstring);
1081 fflush (stdout);
1083 g_free (string);
1087 * g_set_printerr_handler:
1088 * @func: the new error message handler
1090 * Sets the handler for printing error messages.
1092 * Any messages passed to g_printerr() will be output via
1093 * the new handler. The default handler simply outputs the
1094 * message to stderr. By providing your own handler you can
1095 * redirect the output, to a GTK+ widget or a log file for
1096 * example.
1098 * Returns: the old error message handler
1100 GPrintFunc
1101 g_set_printerr_handler (GPrintFunc func)
1103 GPrintFunc old_printerr_func;
1105 g_mutex_lock (g_messages_lock);
1106 old_printerr_func = glib_printerr_func;
1107 glib_printerr_func = func;
1108 g_mutex_unlock (g_messages_lock);
1110 return old_printerr_func;
1114 * g_printerr:
1115 * @format: the message format. See the printf() documentation
1116 * @...: the parameters to insert into the format string
1118 * Outputs a formatted message via the error message handler.
1119 * The default handler simply outputs the message to stderr.
1121 * g_printerr() should not be used from within libraries.
1122 * Instead g_log() should be used, or the convenience functions
1123 * g_message(), g_warning() and g_error().
1125 void
1126 g_printerr (const gchar *format,
1127 ...)
1129 va_list args;
1130 gchar *string;
1131 GPrintFunc local_glib_printerr_func;
1133 g_return_if_fail (format != NULL);
1135 va_start (args, format);
1136 string = g_strdup_vprintf (format, args);
1137 va_end (args);
1139 g_mutex_lock (g_messages_lock);
1140 local_glib_printerr_func = glib_printerr_func;
1141 g_mutex_unlock (g_messages_lock);
1143 if (local_glib_printerr_func)
1144 local_glib_printerr_func (string);
1145 else
1147 const gchar *charset;
1149 if (g_get_charset (&charset))
1150 fputs (string, stderr); /* charset is UTF-8 already */
1151 else
1153 gchar *lstring = strdup_convert (string, charset);
1155 fputs (lstring, stderr);
1156 g_free (lstring);
1158 fflush (stderr);
1160 g_free (string);
1163 gsize
1164 g_printf_string_upper_bound (const gchar *format,
1165 va_list args)
1167 gchar c;
1168 return _g_vsnprintf (&c, 1, format, args) + 1;
1171 void
1172 _g_messages_thread_init_nomessage (void)
1174 g_messages_lock = g_mutex_new ();
1175 g_log_depth = g_private_new (NULL);
1176 g_messages_prefixed_init ();
1177 _g_debug_init ();
1180 gboolean _g_debug_initialized = FALSE;
1181 guint _g_debug_flags = 0;
1183 void
1184 _g_debug_init (void)
1186 const gchar *val;
1188 _g_debug_initialized = TRUE;
1190 val = g_getenv ("G_DEBUG");
1191 if (val != NULL)
1193 const GDebugKey keys[] = {
1194 {"fatal_warnings", G_DEBUG_FATAL_WARNINGS},
1195 {"fatal_criticals", G_DEBUG_FATAL_CRITICALS}
1198 _g_debug_flags = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
1201 if (_g_debug_flags & G_DEBUG_FATAL_WARNINGS)
1203 GLogLevelFlags fatal_mask;
1205 fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
1206 fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
1207 g_log_set_always_fatal (fatal_mask);
1210 if (_g_debug_flags & G_DEBUG_FATAL_CRITICALS)
1212 GLogLevelFlags fatal_mask;
1214 fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
1215 fatal_mask |= G_LOG_LEVEL_CRITICAL;
1216 g_log_set_always_fatal (fatal_mask);