gsettings test: fix srcdir != builddir
[glib.git] / glib / gmessages.c
blob26018cd774062738c064db572b17daf478a144f6
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-private.h"
64 #include "glib-init.h"
65 #include "gbacktrace.h"
66 #include "gcharset.h"
67 #include "gconvert.h"
68 #include "genviron.h"
69 #include "gmem.h"
70 #include "gprintfint.h"
71 #include "gtestutils.h"
72 #include "gthread.h"
73 #include "gstrfuncs.h"
74 #include "gstring.h"
75 #include "gpattern.h"
77 #ifdef G_OS_WIN32
78 #include <process.h> /* For getpid() */
79 #include <io.h>
80 # define _WIN32_WINDOWS 0x0401 /* to get IsDebuggerPresent */
81 # include <windows.h>
82 #endif
85 /**
86 * SECTION:messages
87 * @title: Message Logging
88 * @short_description: versatile support for logging messages
89 * with different levels of importance
91 * These functions provide support for logging error messages
92 * or messages used for debugging.
94 * There are several built-in levels of messages, defined in
95 * #GLogLevelFlags. These can be extended with user-defined levels.
98 /**
99 * G_LOG_DOMAIN:
101 * Defines the log domain.
103 * For applications, this is typically left as the default %NULL
104 * (or "") domain. Libraries should define this so that any messages
105 * which they log can be differentiated from messages from other
106 * libraries and application code. But be careful not to define
107 * it in any public header files.
109 * For example, GTK+ uses this in its Makefile.am:
110 * |[
111 * INCLUDES = -DG_LOG_DOMAIN=\"Gtk\"
112 * ]|
116 * G_LOG_FATAL_MASK:
118 * GLib log levels that are considered fatal by default.
122 * GLogFunc:
123 * @log_domain: the log domain of the message
124 * @log_level: the log level of the message (including the
125 * fatal and recursion flags)
126 * @message: the message to process
127 * @user_data: user data, set in g_log_set_handler()
129 * Specifies the prototype of log handler functions.
131 * The default log handler, g_log_default_handler(), automatically appends a
132 * new-line character to @message when printing it. It is advised that any
133 * custom log handler functions behave similarly, so that logging calls in user
134 * code do not need modifying to add a new-line character to the message if the
135 * log handler is changed.
139 * GLogLevelFlags:
140 * @G_LOG_FLAG_RECURSION: internal flag
141 * @G_LOG_FLAG_FATAL: internal flag
142 * @G_LOG_LEVEL_ERROR: log level for errors, see g_error().
143 * This level is also used for messages produced by g_assert().
144 * @G_LOG_LEVEL_CRITICAL: log level for critical messages, see g_critical().
145 * This level is also used for messages produced by g_return_if_fail()
146 * and g_return_val_if_fail().
147 * @G_LOG_LEVEL_WARNING: log level for warnings, see g_warning()
148 * @G_LOG_LEVEL_MESSAGE: log level for messages, see g_message()
149 * @G_LOG_LEVEL_INFO: log level for informational messages
150 * @G_LOG_LEVEL_DEBUG: log level for debug messages, see g_debug()
151 * @G_LOG_LEVEL_MASK: a mask including all log levels
153 * Flags specifying the level of log messages.
155 * It is possible to change how GLib treats messages of the various
156 * levels using g_log_set_handler() and g_log_set_fatal_mask().
160 * g_message:
161 * @...: format string, followed by parameters to insert
162 * into the format string (as with printf())
164 * A convenience function/macro to log a normal message.
166 * If g_log_default_handler() is used as the log handler function, a new-line
167 * character will automatically be appended to @..., and need not be entered
168 * manually.
172 * g_warning:
173 * @...: format string, followed by parameters to insert
174 * into the format string (as with printf())
176 * A convenience function/macro to log a warning message.
178 * You can make warnings fatal at runtime by setting the
179 * <envar>G_DEBUG</envar> environment variable (see
180 * <ulink url="glib-running.html">Running GLib Applications</ulink>).
182 * If g_log_default_handler() is used as the log handler function, a new-line
183 * character will automatically be appended to @..., and need not be entered
184 * manually.
188 * g_critical:
189 * @...: format string, followed by parameters to insert
190 * into the format string (as with printf())
192 * Logs a "critical warning" (#G_LOG_LEVEL_CRITICAL).
193 * It's more or less application-defined what constitutes
194 * a critical vs. a regular warning. You could call
195 * g_log_set_always_fatal() to make critical warnings exit
196 * the program, then use g_critical() for fatal errors, for
197 * example.
199 * You can also make critical warnings fatal at runtime by
200 * setting the <envar>G_DEBUG</envar> environment variable (see
201 * <ulink url="glib-running.html">Running GLib Applications</ulink>).
203 * If g_log_default_handler() is used as the log handler function, a new-line
204 * character will automatically be appended to @..., and need not be entered
205 * manually.
209 * g_error:
210 * @...: format string, followed by parameters to insert
211 * into the format string (as with printf())
213 * A convenience function/macro to log an error message.
215 * Error messages are always fatal, resulting in a call to
216 * abort() to terminate the application. This function will
217 * result in a core dump; don't use it for errors you expect.
218 * Using this function indicates a bug in your program, i.e.
219 * an assertion failure.
221 * If g_log_default_handler() is used as the log handler function, a new-line
222 * character will automatically be appended to @..., and need not be entered
223 * manually.
228 * g_debug:
229 * @...: format string, followed by parameters to insert
230 * into the format string (as with printf())
232 * A convenience function/macro to log a debug message.
234 * If g_log_default_handler() is used as the log handler function, a new-line
235 * character will automatically be appended to @..., and need not be entered
236 * manually.
238 * Since: 2.6
241 /* --- structures --- */
242 typedef struct _GLogDomain GLogDomain;
243 typedef struct _GLogHandler GLogHandler;
244 struct _GLogDomain
246 gchar *log_domain;
247 GLogLevelFlags fatal_mask;
248 GLogHandler *handlers;
249 GLogDomain *next;
251 struct _GLogHandler
253 guint id;
254 GLogLevelFlags log_level;
255 GLogFunc log_func;
256 gpointer data;
257 GLogHandler *next;
261 /* --- variables --- */
262 static GMutex g_messages_lock;
263 static GLogDomain *g_log_domains = NULL;
264 static GPrintFunc glib_print_func = NULL;
265 static GPrintFunc glib_printerr_func = NULL;
266 static GPrivate g_log_depth;
267 static gboolean exit_on_fatal;
268 static GLogFunc default_log_func = g_log_default_handler;
269 static gpointer default_log_data = NULL;
270 static GTestLogFatalFunc fatal_log_func = NULL;
271 static gpointer fatal_log_data;
273 /* --- functions --- */
275 void
276 _g_log_abort (void)
278 if (exit_on_fatal)
279 _exit (1);
280 else
281 abort ();
284 #ifdef G_OS_WIN32
285 # include <windows.h>
286 static gboolean win32_keep_fatal_message = FALSE;
288 /* This default message will usually be overwritten. */
289 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
290 * called with huge strings, is it?
292 static gchar fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
293 static gchar *fatal_msg_ptr = fatal_msg_buf;
295 #undef write
296 static inline int
297 dowrite (int fd,
298 const void *buf,
299 unsigned int len)
301 if (win32_keep_fatal_message)
303 memcpy (fatal_msg_ptr, buf, len);
304 fatal_msg_ptr += len;
305 *fatal_msg_ptr = 0;
306 return len;
309 write (fd, buf, len);
311 return len;
313 #define write(fd, buf, len) dowrite(fd, buf, len)
315 #endif
317 static void
318 write_string (int fd,
319 const gchar *string)
321 int res;
323 res = write (fd, string, strlen (string));
324 while (G_UNLIKELY (res == -1 && errno == EINTR));
327 static GLogDomain*
328 g_log_find_domain_L (const gchar *log_domain)
330 register GLogDomain *domain;
332 domain = g_log_domains;
333 while (domain)
335 if (strcmp (domain->log_domain, log_domain) == 0)
336 return domain;
337 domain = domain->next;
339 return NULL;
342 static GLogDomain*
343 g_log_domain_new_L (const gchar *log_domain)
345 register GLogDomain *domain;
347 domain = g_new (GLogDomain, 1);
348 domain->log_domain = g_strdup (log_domain);
349 domain->fatal_mask = G_LOG_FATAL_MASK;
350 domain->handlers = NULL;
352 domain->next = g_log_domains;
353 g_log_domains = domain;
355 return domain;
358 static void
359 g_log_domain_check_free_L (GLogDomain *domain)
361 if (domain->fatal_mask == G_LOG_FATAL_MASK &&
362 domain->handlers == NULL)
364 register GLogDomain *last, *work;
366 last = NULL;
368 work = g_log_domains;
369 while (work)
371 if (work == domain)
373 if (last)
374 last->next = domain->next;
375 else
376 g_log_domains = domain->next;
377 g_free (domain->log_domain);
378 g_free (domain);
379 break;
381 last = work;
382 work = last->next;
387 static GLogFunc
388 g_log_domain_get_handler_L (GLogDomain *domain,
389 GLogLevelFlags log_level,
390 gpointer *data)
392 if (domain && log_level)
394 register GLogHandler *handler;
396 handler = domain->handlers;
397 while (handler)
399 if ((handler->log_level & log_level) == log_level)
401 *data = handler->data;
402 return handler->log_func;
404 handler = handler->next;
408 *data = default_log_data;
409 return default_log_func;
413 * g_log_set_always_fatal:
414 * @fatal_mask: the mask containing bits set for each level
415 * of error which is to be fatal
417 * Sets the message levels which are always fatal, in any log domain.
418 * When a message with any of these levels is logged the program terminates.
419 * You can only set the levels defined by GLib to be fatal.
420 * %G_LOG_LEVEL_ERROR is always fatal.
422 * You can also make some message levels fatal at runtime by setting
423 * the <envar>G_DEBUG</envar> environment variable (see
424 * <ulink url="glib-running.html">Running GLib Applications</ulink>).
426 * Returns: the old fatal mask
428 GLogLevelFlags
429 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
431 GLogLevelFlags old_mask;
433 /* restrict the global mask to levels that are known to glib
434 * since this setting applies to all domains
436 fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
437 /* force errors to be fatal */
438 fatal_mask |= G_LOG_LEVEL_ERROR;
439 /* remove bogus flag */
440 fatal_mask &= ~G_LOG_FLAG_FATAL;
442 g_mutex_lock (&g_messages_lock);
443 old_mask = g_log_always_fatal;
444 g_log_always_fatal = fatal_mask;
445 g_mutex_unlock (&g_messages_lock);
447 return old_mask;
451 * g_log_set_fatal_mask:
452 * @log_domain: the log domain
453 * @fatal_mask: the new fatal mask
455 * Sets the log levels which are fatal in the given domain.
456 * %G_LOG_LEVEL_ERROR is always fatal.
458 * Returns: the old fatal mask for the log domain
460 GLogLevelFlags
461 g_log_set_fatal_mask (const gchar *log_domain,
462 GLogLevelFlags fatal_mask)
464 GLogLevelFlags old_flags;
465 register GLogDomain *domain;
467 if (!log_domain)
468 log_domain = "";
470 /* force errors to be fatal */
471 fatal_mask |= G_LOG_LEVEL_ERROR;
472 /* remove bogus flag */
473 fatal_mask &= ~G_LOG_FLAG_FATAL;
475 g_mutex_lock (&g_messages_lock);
477 domain = g_log_find_domain_L (log_domain);
478 if (!domain)
479 domain = g_log_domain_new_L (log_domain);
480 old_flags = domain->fatal_mask;
482 domain->fatal_mask = fatal_mask;
483 g_log_domain_check_free_L (domain);
485 g_mutex_unlock (&g_messages_lock);
487 return old_flags;
491 * g_log_set_handler:
492 * @log_domain: (allow-none): the log domain, or %NULL for the default ""
493 * application domain
494 * @log_levels: the log levels to apply the log handler for.
495 * To handle fatal and recursive messages as well, combine
496 * the log levels with the #G_LOG_FLAG_FATAL and
497 * #G_LOG_FLAG_RECURSION bit flags.
498 * @log_func: the log handler function
499 * @user_data: data passed to the log handler
501 * Sets the log handler for a domain and a set of log levels.
502 * To handle fatal and recursive messages the @log_levels parameter
503 * must be combined with the #G_LOG_FLAG_FATAL and #G_LOG_FLAG_RECURSION
504 * bit flags.
506 * Note that since the #G_LOG_LEVEL_ERROR log level is always fatal, if
507 * you want to set a handler for this log level you must combine it with
508 * #G_LOG_FLAG_FATAL.
510 * <example>
511 * <title>Adding a log handler for all warning messages in the default
512 * (application) domain</title>
513 * <programlisting>
514 * g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
515 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
516 * </programlisting>
517 * </example>
519 * <example>
520 * <title>Adding a log handler for all critical messages from GTK+</title>
521 * <programlisting>
522 * g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
523 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
524 * </programlisting>
525 * </example>
527 * <example>
528 * <title>Adding a log handler for <emphasis>all</emphasis> messages from
529 * GLib</title>
530 * <programlisting>
531 * g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
532 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
533 * </programlisting>
534 * </example>
536 * Returns: the id of the new handler
538 guint
539 g_log_set_handler (const gchar *log_domain,
540 GLogLevelFlags log_levels,
541 GLogFunc log_func,
542 gpointer user_data)
544 static guint handler_id = 0;
545 GLogDomain *domain;
546 GLogHandler *handler;
548 g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
549 g_return_val_if_fail (log_func != NULL, 0);
551 if (!log_domain)
552 log_domain = "";
554 handler = g_new (GLogHandler, 1);
556 g_mutex_lock (&g_messages_lock);
558 domain = g_log_find_domain_L (log_domain);
559 if (!domain)
560 domain = g_log_domain_new_L (log_domain);
562 handler->id = ++handler_id;
563 handler->log_level = log_levels;
564 handler->log_func = log_func;
565 handler->data = user_data;
566 handler->next = domain->handlers;
567 domain->handlers = handler;
569 g_mutex_unlock (&g_messages_lock);
571 return handler_id;
575 * g_log_set_default_handler:
576 * @log_func: the log handler function
577 * @user_data: data passed to the log handler
579 * Installs a default log handler which is used if no
580 * log handler has been set for the particular log domain
581 * and log level combination. By default, GLib uses
582 * g_log_default_handler() as default log handler.
584 * Returns: the previous default log handler
586 * Since: 2.6
588 GLogFunc
589 g_log_set_default_handler (GLogFunc log_func,
590 gpointer user_data)
592 GLogFunc old_log_func;
594 g_mutex_lock (&g_messages_lock);
595 old_log_func = default_log_func;
596 default_log_func = log_func;
597 default_log_data = user_data;
598 g_mutex_unlock (&g_messages_lock);
600 return old_log_func;
604 * g_test_log_set_fatal_handler:
605 * @log_func: the log handler function.
606 * @user_data: data passed to the log handler.
608 * Installs a non-error fatal log handler which can be
609 * used to decide whether log messages which are counted
610 * as fatal abort the program.
612 * The use case here is that you are running a test case
613 * that depends on particular libraries or circumstances
614 * and cannot prevent certain known critical or warning
615 * messages. So you install a handler that compares the
616 * domain and message to precisely not abort in such a case.
618 * Note that the handler is reset at the beginning of
619 * any test case, so you have to set it inside each test
620 * function which needs the special behavior.
622 * This handler has no effect on g_error messages.
624 * Since: 2.22
626 void
627 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
628 gpointer user_data)
630 g_mutex_lock (&g_messages_lock);
631 fatal_log_func = log_func;
632 fatal_log_data = user_data;
633 g_mutex_unlock (&g_messages_lock);
637 * g_log_remove_handler:
638 * @log_domain: the log domain
639 * @handler_id: the id of the handler, which was returned
640 * in g_log_set_handler()
642 * Removes the log handler.
644 void
645 g_log_remove_handler (const gchar *log_domain,
646 guint handler_id)
648 register GLogDomain *domain;
650 g_return_if_fail (handler_id > 0);
652 if (!log_domain)
653 log_domain = "";
655 g_mutex_lock (&g_messages_lock);
656 domain = g_log_find_domain_L (log_domain);
657 if (domain)
659 GLogHandler *work, *last;
661 last = NULL;
662 work = domain->handlers;
663 while (work)
665 if (work->id == handler_id)
667 if (last)
668 last->next = work->next;
669 else
670 domain->handlers = work->next;
671 g_log_domain_check_free_L (domain);
672 g_mutex_unlock (&g_messages_lock);
673 g_free (work);
674 return;
676 last = work;
677 work = last->next;
680 g_mutex_unlock (&g_messages_lock);
681 g_warning ("%s: could not find handler with id '%d' for domain \"%s\"",
682 G_STRLOC, handler_id, log_domain);
685 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
686 (wc == 0x7f) || \
687 (wc >= 0x80 && wc < 0xa0)))
689 static gchar*
690 strdup_convert (const gchar *string,
691 const gchar *charset)
693 if (!g_utf8_validate (string, -1, NULL))
695 GString *gstring = g_string_new ("[Invalid UTF-8] ");
696 guchar *p;
698 for (p = (guchar *)string; *p; p++)
700 if (CHAR_IS_SAFE(*p) &&
701 !(*p == '\r' && *(p + 1) != '\n') &&
702 *p < 0x80)
703 g_string_append_c (gstring, *p);
704 else
705 g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
708 return g_string_free (gstring, FALSE);
710 else
712 GError *err = NULL;
714 gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
715 if (result)
716 return result;
717 else
719 /* Not thread-safe, but doesn't matter if we print the warning twice
721 static gboolean warned = FALSE;
722 if (!warned)
724 warned = TRUE;
725 _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
727 g_error_free (err);
729 return g_strdup (string);
734 /* For a radix of 8 we need at most 3 output bytes for 1 input
735 * byte. Additionally we might need up to 2 output bytes for the
736 * readix prefix and 1 byte for the trailing NULL.
738 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
740 static void
741 format_unsigned (gchar *buf,
742 gulong num,
743 guint radix)
745 gulong tmp;
746 gchar c;
747 gint i, n;
749 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
751 if (radix != 8 && radix != 10 && radix != 16)
753 *buf = '\000';
754 return;
757 if (!num)
759 *buf++ = '0';
760 *buf = '\000';
761 return;
764 if (radix == 16)
766 *buf++ = '0';
767 *buf++ = 'x';
769 else if (radix == 8)
771 *buf++ = '0';
774 n = 0;
775 tmp = num;
776 while (tmp)
778 tmp /= radix;
779 n++;
782 i = n;
784 /* Again we can't use g_assert; actually this check should _never_ fail. */
785 if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
787 *buf = '\000';
788 return;
791 while (num)
793 i--;
794 c = (num % radix);
795 if (c < 10)
796 buf[i] = c + '0';
797 else
798 buf[i] = c + 'a' - 10;
799 num /= radix;
802 buf[n] = '\000';
805 /* string size big enough to hold level prefix */
806 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
808 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
810 /* these are emitted by the default log handler */
811 #define DEFAULT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE)
812 /* these are filtered by G_MESSAGES_DEBUG by the default log handler */
813 #define INFO_LEVELS (G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG)
815 static int
816 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
817 GLogLevelFlags log_level)
819 gboolean to_stdout = TRUE;
821 /* we may not call _any_ GLib functions here */
823 switch (log_level & G_LOG_LEVEL_MASK)
825 case G_LOG_LEVEL_ERROR:
826 strcpy (level_prefix, "ERROR");
827 to_stdout = FALSE;
828 break;
829 case G_LOG_LEVEL_CRITICAL:
830 strcpy (level_prefix, "CRITICAL");
831 to_stdout = FALSE;
832 break;
833 case G_LOG_LEVEL_WARNING:
834 strcpy (level_prefix, "WARNING");
835 to_stdout = FALSE;
836 break;
837 case G_LOG_LEVEL_MESSAGE:
838 strcpy (level_prefix, "Message");
839 to_stdout = FALSE;
840 break;
841 case G_LOG_LEVEL_INFO:
842 strcpy (level_prefix, "INFO");
843 break;
844 case G_LOG_LEVEL_DEBUG:
845 strcpy (level_prefix, "DEBUG");
846 break;
847 default:
848 if (log_level)
850 strcpy (level_prefix, "LOG-");
851 format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
853 else
854 strcpy (level_prefix, "LOG");
855 break;
857 if (log_level & G_LOG_FLAG_RECURSION)
858 strcat (level_prefix, " (recursed)");
859 if (log_level & ALERT_LEVELS)
860 strcat (level_prefix, " **");
862 #ifdef G_OS_WIN32
863 if ((log_level & G_LOG_FLAG_FATAL) != 0 && !g_test_initialized ())
864 win32_keep_fatal_message = TRUE;
865 #endif
866 return to_stdout ? 1 : 2;
869 typedef struct {
870 gchar *log_domain;
871 GLogLevelFlags log_level;
872 gchar *pattern;
873 } GTestExpectedMessage;
875 static GSList *expected_messages = NULL;
878 * g_logv:
879 * @log_domain: the log domain
880 * @log_level: the log level
881 * @format: the message format. See the printf() documentation
882 * @args: the parameters to insert into the format string
884 * Logs an error or debugging message.
886 * If the log level has been set as fatal, the abort()
887 * function is called to terminate the program.
889 * If g_log_default_handler() is used as the log handler function, a new-line
890 * character will automatically be appended to @..., and need not be entered
891 * manually.
893 void
894 g_logv (const gchar *log_domain,
895 GLogLevelFlags log_level,
896 const gchar *format,
897 va_list args)
899 gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
900 gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
901 gchar buffer[1025], *msg, *msg_alloc = NULL;
902 gint i;
904 log_level &= G_LOG_LEVEL_MASK;
905 if (!log_level)
906 return;
908 if (log_level & G_LOG_FLAG_RECURSION)
910 /* we use a stack buffer of fixed size, since we're likely
911 * in an out-of-memory situation
913 gsize size G_GNUC_UNUSED;
915 size = _g_vsnprintf (buffer, 1024, format, args);
916 msg = buffer;
918 else
919 msg = msg_alloc = g_strdup_vprintf (format, args);
921 if (expected_messages)
923 GTestExpectedMessage *expected = expected_messages->data;
925 if (g_strcmp0 (expected->log_domain, log_domain) == 0 &&
926 ((log_level & expected->log_level) == expected->log_level) &&
927 g_pattern_match_simple (expected->pattern, msg))
929 expected_messages = g_slist_delete_link (expected_messages,
930 expected_messages);
931 g_free (expected->log_domain);
932 g_free (expected->pattern);
933 g_free (expected);
934 g_free (msg_alloc);
935 return;
937 else if ((log_level & G_LOG_LEVEL_DEBUG) != G_LOG_LEVEL_DEBUG)
939 gchar level_prefix[STRING_BUFFER_SIZE];
940 gchar *expected_message;
942 mklevel_prefix (level_prefix, expected->log_level);
943 expected_message = g_strdup_printf ("Did not see expected message %s: %s",
944 level_prefix, expected->pattern);
945 g_log_default_handler (log_domain, log_level, expected_message, NULL);
946 g_free (expected_message);
948 log_level |= G_LOG_FLAG_FATAL;
952 for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
954 register GLogLevelFlags test_level;
956 test_level = 1 << i;
957 if (log_level & test_level)
959 GLogDomain *domain;
960 GLogFunc log_func;
961 GLogLevelFlags domain_fatal_mask;
962 gpointer data = NULL;
963 gboolean masquerade_fatal = FALSE;
964 guint depth;
966 if (was_fatal)
967 test_level |= G_LOG_FLAG_FATAL;
968 if (was_recursion)
969 test_level |= G_LOG_FLAG_RECURSION;
971 /* check recursion and lookup handler */
972 g_mutex_lock (&g_messages_lock);
973 depth = GPOINTER_TO_UINT (g_private_get (&g_log_depth));
974 domain = g_log_find_domain_L (log_domain ? log_domain : "");
975 if (depth)
976 test_level |= G_LOG_FLAG_RECURSION;
977 depth++;
978 domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
979 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
980 test_level |= G_LOG_FLAG_FATAL;
981 if (test_level & G_LOG_FLAG_RECURSION)
982 log_func = _g_log_fallback_handler;
983 else
984 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
985 domain = NULL;
986 g_mutex_unlock (&g_messages_lock);
988 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
990 log_func (log_domain, test_level, msg, data);
992 if ((test_level & G_LOG_FLAG_FATAL)
993 && !(test_level & G_LOG_LEVEL_ERROR))
995 masquerade_fatal = fatal_log_func
996 && !fatal_log_func (log_domain, test_level, msg, fatal_log_data);
999 if ((test_level & G_LOG_FLAG_FATAL) && exit_on_fatal && !masquerade_fatal)
1001 _g_log_abort ();
1003 else if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
1005 #ifdef G_OS_WIN32
1006 if (win32_keep_fatal_message)
1008 gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
1010 MessageBox (NULL, locale_msg, NULL,
1011 MB_ICONERROR|MB_SETFOREGROUND);
1013 if (IsDebuggerPresent () && !(test_level & G_LOG_FLAG_RECURSION))
1014 G_BREAKPOINT ();
1015 else
1016 abort ();
1017 #else
1018 if (!(test_level & G_LOG_FLAG_RECURSION))
1019 G_BREAKPOINT ();
1020 else
1021 abort ();
1022 #endif /* !G_OS_WIN32 */
1025 depth--;
1026 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1030 g_free (msg_alloc);
1034 * g_log:
1035 * @log_domain: the log domain, usually #G_LOG_DOMAIN
1036 * @log_level: the log level, either from #GLogLevelFlags
1037 * or a user-defined level
1038 * @format: the message format. See the printf() documentation
1039 * @...: the parameters to insert into the format string
1041 * Logs an error or debugging message.
1043 * If the log level has been set as fatal, the abort()
1044 * function is called to terminate the program.
1046 * If g_log_default_handler() is used as the log handler function, a new-line
1047 * character will automatically be appended to @..., and need not be entered
1048 * manually.
1050 void
1051 g_log (const gchar *log_domain,
1052 GLogLevelFlags log_level,
1053 const gchar *format,
1054 ...)
1056 va_list args;
1058 va_start (args, format);
1059 g_logv (log_domain, log_level, format, args);
1060 va_end (args);
1063 void
1064 g_return_if_fail_warning (const char *log_domain,
1065 const char *pretty_function,
1066 const char *expression)
1068 g_log (log_domain,
1069 G_LOG_LEVEL_CRITICAL,
1070 "%s: assertion '%s' failed",
1071 pretty_function,
1072 expression);
1075 void
1076 g_warn_message (const char *domain,
1077 const char *file,
1078 int line,
1079 const char *func,
1080 const char *warnexpr)
1082 char *s, lstr[32];
1083 g_snprintf (lstr, 32, "%d", line);
1084 if (warnexpr)
1085 s = g_strconcat ("(", file, ":", lstr, "):",
1086 func, func[0] ? ":" : "",
1087 " runtime check failed: (", warnexpr, ")", NULL);
1088 else
1089 s = g_strconcat ("(", file, ":", lstr, "):",
1090 func, func[0] ? ":" : "",
1091 " ", "code should not be reached", NULL);
1092 g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
1093 g_free (s);
1096 void
1097 g_assert_warning (const char *log_domain,
1098 const char *file,
1099 const int line,
1100 const char *pretty_function,
1101 const char *expression)
1103 g_log (log_domain,
1104 G_LOG_LEVEL_ERROR,
1105 expression
1106 ? "file %s: line %d (%s): assertion failed: (%s)"
1107 : "file %s: line %d (%s): should not be reached",
1108 file,
1109 line,
1110 pretty_function,
1111 expression);
1112 _g_log_abort ();
1116 * g_test_expect_message:
1117 * @log_domain: (allow-none): the log domain of the message
1118 * @log_level: the log level of the message
1119 * @pattern: a glob-style
1120 * <link linkend="glib-Glob-style-pattern-matching">pattern</link>
1122 * Indicates that a message with the given @log_domain and @log_level,
1123 * with text matching @pattern, is expected to be logged. When this
1124 * message is logged, it will not be printed, and the test case will
1125 * not abort.
1127 * Use g_test_assert_expected_messages() to assert that all
1128 * previously-expected messages have been seen and suppressed.
1130 * You can call this multiple times in a row, if multiple messages are
1131 * expected as a result of a single call. (The messages must appear in
1132 * the same order as the calls to g_test_expect_message().)
1134 * For example:
1136 * |[
1137 * /&ast; g_main_context_push_thread_default() should fail if the
1138 * &ast; context is already owned by another thread.
1139 * &ast;/
1140 * g_test_expect_message (G_LOG_DOMAIN,
1141 * G_LOG_LEVEL_CRITICAL,
1142 * "assertion*acquired_context*failed");
1143 * g_main_context_push_thread_default (bad_context);
1144 * g_test_assert_expected_messages ();
1145 * ]|
1147 * Note that you cannot use this to test g_error() messages, since
1148 * g_error() intentionally never returns even if the program doesn't
1149 * abort; use g_test_trap_subprocess() in this case.
1151 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
1152 * expected via g_test_expect_message() then they will be ignored.
1154 * Since: 2.34
1156 void
1157 g_test_expect_message (const gchar *log_domain,
1158 GLogLevelFlags log_level,
1159 const gchar *pattern)
1161 GTestExpectedMessage *expected;
1163 g_return_if_fail (log_level != 0);
1164 g_return_if_fail (pattern != NULL);
1165 g_return_if_fail (~log_level & G_LOG_LEVEL_ERROR);
1167 expected = g_new (GTestExpectedMessage, 1);
1168 expected->log_domain = g_strdup (log_domain);
1169 expected->log_level = log_level;
1170 expected->pattern = g_strdup (pattern);
1172 expected_messages = g_slist_append (expected_messages, expected);
1175 void
1176 g_test_assert_expected_messages_internal (const char *domain,
1177 const char *file,
1178 int line,
1179 const char *func)
1181 if (expected_messages)
1183 GTestExpectedMessage *expected;
1184 gchar level_prefix[STRING_BUFFER_SIZE];
1185 gchar *message;
1187 expected = expected_messages->data;
1189 mklevel_prefix (level_prefix, expected->log_level);
1190 message = g_strdup_printf ("Did not see expected message %s: %s",
1191 level_prefix, expected->pattern);
1192 g_assertion_message (domain, file, line, func, message);
1193 g_free (message);
1198 * g_test_assert_expected_messages:
1200 * Asserts that all messages previously indicated via
1201 * g_test_expect_message() have been seen and suppressed.
1203 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
1204 * expected via g_test_expect_message() then they will be ignored.
1206 * Since: 2.34
1209 void
1210 _g_log_fallback_handler (const gchar *log_domain,
1211 GLogLevelFlags log_level,
1212 const gchar *message,
1213 gpointer unused_data)
1215 gchar level_prefix[STRING_BUFFER_SIZE];
1216 #ifndef G_OS_WIN32
1217 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
1218 #endif
1219 int fd;
1221 /* we cannot call _any_ GLib functions in this fallback handler,
1222 * which is why we skip UTF-8 conversion, etc.
1223 * since we either recursed or ran out of memory, we're in a pretty
1224 * pathologic situation anyways, what we can do is giving the
1225 * the process ID unconditionally however.
1228 fd = mklevel_prefix (level_prefix, log_level);
1229 if (!message)
1230 message = "(NULL) message";
1232 #ifndef G_OS_WIN32
1233 format_unsigned (pid_string, getpid (), 10);
1234 #endif
1236 if (log_domain)
1237 write_string (fd, "\n");
1238 else
1239 write_string (fd, "\n** ");
1241 #ifndef G_OS_WIN32
1242 write_string (fd, "(process:");
1243 write_string (fd, pid_string);
1244 write_string (fd, "): ");
1245 #endif
1247 if (log_domain)
1249 write_string (fd, log_domain);
1250 write_string (fd, "-");
1252 write_string (fd, level_prefix);
1253 write_string (fd, ": ");
1254 write_string (fd, message);
1257 static void
1258 escape_string (GString *string)
1260 const char *p = string->str;
1261 gunichar wc;
1263 while (p < string->str + string->len)
1265 gboolean safe;
1267 wc = g_utf8_get_char_validated (p, -1);
1268 if (wc == (gunichar)-1 || wc == (gunichar)-2)
1270 gchar *tmp;
1271 guint pos;
1273 pos = p - string->str;
1275 /* Emit invalid UTF-8 as hex escapes
1277 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
1278 g_string_erase (string, pos, 1);
1279 g_string_insert (string, pos, tmp);
1281 p = string->str + (pos + 4); /* Skip over escape sequence */
1283 g_free (tmp);
1284 continue;
1286 if (wc == '\r')
1288 safe = *(p + 1) == '\n';
1290 else
1292 safe = CHAR_IS_SAFE (wc);
1295 if (!safe)
1297 gchar *tmp;
1298 guint pos;
1300 pos = p - string->str;
1302 /* Largest char we escape is 0x0a, so we don't have to worry
1303 * about 8-digit \Uxxxxyyyy
1305 tmp = g_strdup_printf ("\\u%04x", wc);
1306 g_string_erase (string, pos, g_utf8_next_char (p) - p);
1307 g_string_insert (string, pos, tmp);
1308 g_free (tmp);
1310 p = string->str + (pos + 6); /* Skip over escape sequence */
1312 else
1313 p = g_utf8_next_char (p);
1318 * g_log_default_handler:
1319 * @log_domain: the log domain of the message
1320 * @log_level: the level of the message
1321 * @message: the message
1322 * @unused_data: data passed from g_log() which is unused
1324 * The default log handler set up by GLib; g_log_set_default_handler()
1325 * allows to install an alternate default log handler.
1326 * This is used if no log handler has been set for the particular log
1327 * domain and log level combination. It outputs the message to stderr
1328 * or stdout and if the log level is fatal it calls abort(). It automatically
1329 * prints a new-line character after the message, so one does not need to be
1330 * manually included in @message.
1332 * The behavior of this log handler can be influenced by a number of
1333 * environment variables:
1334 * <variablelist>
1335 * <varlistentry>
1336 * <term><envar>G_MESSAGES_PREFIXED</envar></term>
1337 * <listitem>
1338 * A :-separated list of log levels for which messages should
1339 * be prefixed by the program name and PID of the aplication.
1340 * </listitem>
1341 * </varlistentry>
1342 * <varlistentry>
1343 * <term><envar>G_MESSAGES_DEBUG</envar></term>
1344 * <listitem>
1345 * A space-separated list of log domains for which debug and
1346 * informational messages are printed. By default these
1347 * messages are not printed.
1348 * </listitem>
1349 * </varlistentry>
1350 * </variablelist>
1352 * stderr is used for levels %G_LOG_LEVEL_ERROR, %G_LOG_LEVEL_CRITICAL,
1353 * %G_LOG_LEVEL_WARNING and %G_LOG_LEVEL_MESSAGE. stdout is used for
1354 * the rest.
1356 void
1357 g_log_default_handler (const gchar *log_domain,
1358 GLogLevelFlags log_level,
1359 const gchar *message,
1360 gpointer unused_data)
1362 gchar level_prefix[STRING_BUFFER_SIZE], *string;
1363 GString *gstring;
1364 int fd;
1365 const gchar *domains;
1367 if ((log_level & DEFAULT_LEVELS) || (log_level >> G_LOG_LEVEL_USER_SHIFT))
1368 goto emit;
1370 domains = g_getenv ("G_MESSAGES_DEBUG");
1371 if (((log_level & INFO_LEVELS) == 0) ||
1372 domains == NULL ||
1373 (strcmp (domains, "all") != 0 && (!log_domain || !strstr (domains, log_domain))))
1374 return;
1376 emit:
1377 /* we can be called externally with recursion for whatever reason */
1378 if (log_level & G_LOG_FLAG_RECURSION)
1380 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
1381 return;
1384 fd = mklevel_prefix (level_prefix, log_level);
1386 gstring = g_string_new (NULL);
1387 if (log_level & ALERT_LEVELS)
1388 g_string_append (gstring, "\n");
1389 if (!log_domain)
1390 g_string_append (gstring, "** ");
1392 if ((g_log_msg_prefix & (log_level & G_LOG_LEVEL_MASK)) == (log_level & G_LOG_LEVEL_MASK))
1394 const gchar *prg_name = g_get_prgname ();
1396 if (!prg_name)
1397 g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
1398 else
1399 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
1402 if (log_domain)
1404 g_string_append (gstring, log_domain);
1405 g_string_append_c (gstring, '-');
1407 g_string_append (gstring, level_prefix);
1409 g_string_append (gstring, ": ");
1410 if (!message)
1411 g_string_append (gstring, "(NULL) message");
1412 else
1414 GString *msg;
1415 const gchar *charset;
1417 msg = g_string_new (message);
1418 escape_string (msg);
1420 if (g_get_charset (&charset))
1421 g_string_append (gstring, msg->str); /* charset is UTF-8 already */
1422 else
1424 string = strdup_convert (msg->str, charset);
1425 g_string_append (gstring, string);
1426 g_free (string);
1429 g_string_free (msg, TRUE);
1431 g_string_append (gstring, "\n");
1433 string = g_string_free (gstring, FALSE);
1435 write_string (fd, string);
1436 g_free (string);
1440 * g_set_print_handler:
1441 * @func: the new print handler
1443 * Sets the print handler.
1445 * Any messages passed to g_print() will be output via
1446 * the new handler. The default handler simply outputs
1447 * the message to stdout. By providing your own handler
1448 * you can redirect the output, to a GTK+ widget or a
1449 * log file for example.
1451 * Returns: the old print handler
1453 GPrintFunc
1454 g_set_print_handler (GPrintFunc func)
1456 GPrintFunc old_print_func;
1458 g_mutex_lock (&g_messages_lock);
1459 old_print_func = glib_print_func;
1460 glib_print_func = func;
1461 g_mutex_unlock (&g_messages_lock);
1463 return old_print_func;
1467 * g_print:
1468 * @format: the message format. See the printf() documentation
1469 * @...: the parameters to insert into the format string
1471 * Outputs a formatted message via the print handler.
1472 * The default print handler simply outputs the message to stdout, without
1473 * appending a trailing new-line character. Typically, @format should end with
1474 * its own new-line character.
1476 * g_print() should not be used from within libraries for debugging
1477 * messages, since it may be redirected by applications to special
1478 * purpose message windows or even files. Instead, libraries should
1479 * use g_log(), or the convenience functions g_message(), g_warning()
1480 * and g_error().
1482 void
1483 g_print (const gchar *format,
1484 ...)
1486 va_list args;
1487 gchar *string;
1488 GPrintFunc local_glib_print_func;
1490 g_return_if_fail (format != NULL);
1492 va_start (args, format);
1493 string = g_strdup_vprintf (format, args);
1494 va_end (args);
1496 g_mutex_lock (&g_messages_lock);
1497 local_glib_print_func = glib_print_func;
1498 g_mutex_unlock (&g_messages_lock);
1500 if (local_glib_print_func)
1501 local_glib_print_func (string);
1502 else
1504 const gchar *charset;
1506 if (g_get_charset (&charset))
1507 fputs (string, stdout); /* charset is UTF-8 already */
1508 else
1510 gchar *lstring = strdup_convert (string, charset);
1512 fputs (lstring, stdout);
1513 g_free (lstring);
1515 fflush (stdout);
1517 g_free (string);
1521 * g_set_printerr_handler:
1522 * @func: the new error message handler
1524 * Sets the handler for printing error messages.
1526 * Any messages passed to g_printerr() will be output via
1527 * the new handler. The default handler simply outputs the
1528 * message to stderr. By providing your own handler you can
1529 * redirect the output, to a GTK+ widget or a log file for
1530 * example.
1532 * Returns: the old error message handler
1534 GPrintFunc
1535 g_set_printerr_handler (GPrintFunc func)
1537 GPrintFunc old_printerr_func;
1539 g_mutex_lock (&g_messages_lock);
1540 old_printerr_func = glib_printerr_func;
1541 glib_printerr_func = func;
1542 g_mutex_unlock (&g_messages_lock);
1544 return old_printerr_func;
1548 * g_printerr:
1549 * @format: the message format. See the printf() documentation
1550 * @...: the parameters to insert into the format string
1552 * Outputs a formatted message via the error message handler.
1553 * The default handler simply outputs the message to stderr, without appending
1554 * a trailing new-line character. Typically, @format should end with its own
1555 * new-line character.
1557 * g_printerr() should not be used from within libraries.
1558 * Instead g_log() should be used, or the convenience functions
1559 * g_message(), g_warning() and g_error().
1561 void
1562 g_printerr (const gchar *format,
1563 ...)
1565 va_list args;
1566 gchar *string;
1567 GPrintFunc local_glib_printerr_func;
1569 g_return_if_fail (format != NULL);
1571 va_start (args, format);
1572 string = g_strdup_vprintf (format, args);
1573 va_end (args);
1575 g_mutex_lock (&g_messages_lock);
1576 local_glib_printerr_func = glib_printerr_func;
1577 g_mutex_unlock (&g_messages_lock);
1579 if (local_glib_printerr_func)
1580 local_glib_printerr_func (string);
1581 else
1583 const gchar *charset;
1585 if (g_get_charset (&charset))
1586 fputs (string, stderr); /* charset is UTF-8 already */
1587 else
1589 gchar *lstring = strdup_convert (string, charset);
1591 fputs (lstring, stderr);
1592 g_free (lstring);
1594 fflush (stderr);
1596 g_free (string);
1600 * g_printf_string_upper_bound:
1601 * @format: the format string. See the printf() documentation
1602 * @args: the parameters to be inserted into the format string
1604 * Calculates the maximum space needed to store the output
1605 * of the sprintf() function.
1607 * Returns: the maximum space needed to store the formatted string
1609 gsize
1610 g_printf_string_upper_bound (const gchar *format,
1611 va_list args)
1613 gchar c;
1614 return _g_vsnprintf (&c, 1, format, args) + 1;
1617 void
1618 _g_log_set_exit_on_fatal (void)
1620 exit_on_fatal = TRUE;