Updated Hungarian translation
[glib.git] / glib / gmessages.c
blobc1b5622a12b1bcf832f989670a65f342ed4d34df
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, see <http://www.gnu.org/licenses/>.
19 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
20 * file for a list of people on the GLib Team. See the ChangeLog
21 * files for a list of changes. These files are distributed with
22 * GLib at ftp://ftp.gtk.org/pub/gtk/.
26 * MT safe
29 /**
30 * SECTION:warnings
31 * @Title: Message Output and Debugging Functions
32 * @Short_description: functions to output messages and help debug applications
34 * These functions provide support for outputting messages.
36 * The g_return family of macros (g_return_if_fail(),
37 * g_return_val_if_fail(), g_return_if_reached(),
38 * g_return_val_if_reached()) should only be used for programming
39 * errors, a typical use case is checking for invalid parameters at
40 * the beginning of a public function. They should not be used if
41 * you just mean "if (error) return", they should only be used if
42 * you mean "if (bug in program) return". The program behavior is
43 * generally considered undefined after one of these checks fails.
44 * They are not intended for normal control flow, only to give a
45 * perhaps-helpful warning before giving up.
48 #include "config.h"
50 #include <stdlib.h>
51 #include <stdarg.h>
52 #include <stdio.h>
53 #include <string.h>
54 #include <signal.h>
55 #include <locale.h>
56 #include <errno.h>
58 #include "glib-init.h"
59 #include "gbacktrace.h"
60 #include "gcharset.h"
61 #include "gconvert.h"
62 #include "genviron.h"
63 #include "gmem.h"
64 #include "gprintfint.h"
65 #include "gtestutils.h"
66 #include "gthread.h"
67 #include "gstrfuncs.h"
68 #include "gstring.h"
69 #include "gpattern.h"
71 #ifdef G_OS_UNIX
72 #include <unistd.h>
73 #endif
75 #ifdef G_OS_WIN32
76 #include <process.h> /* For getpid() */
77 #include <io.h>
78 # define _WIN32_WINDOWS 0x0401 /* to get IsDebuggerPresent */
79 # include <windows.h>
80 #endif
83 /**
84 * SECTION:messages
85 * @title: Message Logging
86 * @short_description: versatile support for logging messages
87 * with different levels of importance
89 * These functions provide support for logging error messages
90 * or messages used for debugging.
92 * There are several built-in levels of messages, defined in
93 * #GLogLevelFlags. These can be extended with user-defined levels.
96 /**
97 * G_LOG_DOMAIN:
99 * Defines the log domain.
101 * For applications, this is typically left as the default %NULL
102 * (or "") domain. Libraries should define this so that any messages
103 * which they log can be differentiated from messages from other
104 * libraries and application code. But be careful not to define
105 * it in any public header files.
107 * For example, GTK+ uses this in its Makefile.am:
108 * |[
109 * INCLUDES = -DG_LOG_DOMAIN=\"Gtk\"
110 * ]|
114 * G_LOG_FATAL_MASK:
116 * GLib log levels that are considered fatal by default.
120 * GLogFunc:
121 * @log_domain: the log domain of the message
122 * @log_level: the log level of the message (including the
123 * fatal and recursion flags)
124 * @message: the message to process
125 * @user_data: user data, set in g_log_set_handler()
127 * Specifies the prototype of log handler functions.
129 * The default log handler, g_log_default_handler(), automatically appends a
130 * new-line character to @message when printing it. It is advised that any
131 * custom log handler functions behave similarly, so that logging calls in user
132 * code do not need modifying to add a new-line character to the message if the
133 * log handler is changed.
137 * GLogLevelFlags:
138 * @G_LOG_FLAG_RECURSION: internal flag
139 * @G_LOG_FLAG_FATAL: internal flag
140 * @G_LOG_LEVEL_ERROR: log level for errors, see g_error().
141 * This level is also used for messages produced by g_assert().
142 * @G_LOG_LEVEL_CRITICAL: log level for critical messages, see g_critical().
143 * This level is also used for messages produced by g_return_if_fail()
144 * and g_return_val_if_fail().
145 * @G_LOG_LEVEL_WARNING: log level for warnings, see g_warning()
146 * @G_LOG_LEVEL_MESSAGE: log level for messages, see g_message()
147 * @G_LOG_LEVEL_INFO: log level for informational messages, see g_info()
148 * @G_LOG_LEVEL_DEBUG: log level for debug messages, see g_debug()
149 * @G_LOG_LEVEL_MASK: a mask including all log levels
151 * Flags specifying the level of log messages.
153 * It is possible to change how GLib treats messages of the various
154 * levels using g_log_set_handler() and g_log_set_fatal_mask().
158 * G_LOG_LEVEL_USER_SHIFT:
160 * Log levels below 1<<G_LOG_LEVEL_USER_SHIFT are used by GLib.
161 * Higher bits can be used for user-defined log levels.
165 * g_message:
166 * @...: format string, followed by parameters to insert
167 * into the format string (as with printf())
169 * A convenience function/macro to log a normal message.
171 * If g_log_default_handler() is used as the log handler function, a new-line
172 * character will automatically be appended to @..., and need not be entered
173 * manually.
177 * g_warning:
178 * @...: format string, followed by parameters to insert
179 * into the format string (as with printf())
181 * A convenience function/macro to log a warning message.
183 * You can make warnings fatal at runtime by setting the `G_DEBUG`
184 * environment variable (see
185 * [Running GLib Applications](glib-running.html)).
187 * If g_log_default_handler() is used as the log handler function,
188 * a newline character will automatically be appended to @..., and
189 * need not be entered manually.
193 * g_critical:
194 * @...: format string, followed by parameters to insert
195 * into the format string (as with printf())
197 * Logs a "critical warning" (#G_LOG_LEVEL_CRITICAL).
198 * It's more or less application-defined what constitutes
199 * a critical vs. a regular warning. You could call
200 * g_log_set_always_fatal() to make critical warnings exit
201 * the program, then use g_critical() for fatal errors, for
202 * example.
204 * You can also make critical warnings fatal at runtime by
205 * setting the `G_DEBUG` environment variable (see
206 * [Running GLib Applications](glib-running.html)).
208 * If g_log_default_handler() is used as the log handler function, a new-line
209 * character will automatically be appended to @..., and need not be entered
210 * manually.
214 * g_error:
215 * @...: format string, followed by parameters to insert
216 * into the format string (as with printf())
218 * A convenience function/macro to log an error message.
220 * Error messages are always fatal, resulting in a call to
221 * abort() to terminate the application. This function will
222 * result in a core dump; don't use it for errors you expect.
223 * Using this function indicates a bug in your program, i.e.
224 * an assertion failure.
226 * If g_log_default_handler() is used as the log handler function, a new-line
227 * character will automatically be appended to @..., and need not be entered
228 * manually.
233 * g_info:
234 * @...: format string, followed by parameters to insert
235 * into the format string (as with printf())
237 * A convenience function/macro to log an informational message. Seldom used.
239 * If g_log_default_handler() is used as the log handler function, a new-line
240 * character will automatically be appended to @..., and need not be entered
241 * manually.
243 * Such messages are suppressed by the g_log_default_handler() unless
244 * the G_MESSAGES_DEBUG environment variable is set appropriately.
246 * Since: 2.40
250 * g_debug:
251 * @...: format string, followed by parameters to insert
252 * into the format string (as with printf())
254 * A convenience function/macro to log a debug message.
256 * If g_log_default_handler() is used as the log handler function, a new-line
257 * character will automatically be appended to @..., and need not be entered
258 * manually.
260 * Such messages are suppressed by the g_log_default_handler() unless
261 * the G_MESSAGES_DEBUG environment variable is set appropriately.
263 * Since: 2.6
266 /* --- structures --- */
267 typedef struct _GLogDomain GLogDomain;
268 typedef struct _GLogHandler GLogHandler;
269 struct _GLogDomain
271 gchar *log_domain;
272 GLogLevelFlags fatal_mask;
273 GLogHandler *handlers;
274 GLogDomain *next;
276 struct _GLogHandler
278 guint id;
279 GLogLevelFlags log_level;
280 GLogFunc log_func;
281 gpointer data;
282 GLogHandler *next;
286 /* --- variables --- */
287 static GMutex g_messages_lock;
288 static GLogDomain *g_log_domains = NULL;
289 static GPrintFunc glib_print_func = NULL;
290 static GPrintFunc glib_printerr_func = NULL;
291 static GPrivate g_log_depth;
292 static GLogFunc default_log_func = g_log_default_handler;
293 static gpointer default_log_data = NULL;
294 static GTestLogFatalFunc fatal_log_func = NULL;
295 static gpointer fatal_log_data;
297 /* --- functions --- */
299 static void _g_log_abort (gboolean breakpoint);
301 static void
302 _g_log_abort (gboolean breakpoint)
304 if (g_test_subprocess ())
306 /* If this is a test case subprocess then it probably caused
307 * this error message on purpose, so just exit() rather than
308 * abort()ing, to avoid triggering any system crash-reporting
309 * daemon.
311 _exit (1);
314 if (breakpoint)
315 G_BREAKPOINT ();
316 else
317 abort ();
320 #ifdef G_OS_WIN32
321 # include <windows.h>
322 static gboolean win32_keep_fatal_message = FALSE;
324 /* This default message will usually be overwritten. */
325 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
326 * called with huge strings, is it?
328 static gchar fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
329 static gchar *fatal_msg_ptr = fatal_msg_buf;
331 #undef write
332 static inline int
333 dowrite (int fd,
334 const void *buf,
335 unsigned int len)
337 if (win32_keep_fatal_message)
339 memcpy (fatal_msg_ptr, buf, len);
340 fatal_msg_ptr += len;
341 *fatal_msg_ptr = 0;
342 return len;
345 write (fd, buf, len);
347 return len;
349 #define write(fd, buf, len) dowrite(fd, buf, len)
351 #endif
353 static void
354 write_string (int fd,
355 const gchar *string)
357 int res;
359 res = write (fd, string, strlen (string));
360 while (G_UNLIKELY (res == -1 && errno == EINTR));
363 static GLogDomain*
364 g_log_find_domain_L (const gchar *log_domain)
366 GLogDomain *domain;
368 domain = g_log_domains;
369 while (domain)
371 if (strcmp (domain->log_domain, log_domain) == 0)
372 return domain;
373 domain = domain->next;
375 return NULL;
378 static GLogDomain*
379 g_log_domain_new_L (const gchar *log_domain)
381 GLogDomain *domain;
383 domain = g_new (GLogDomain, 1);
384 domain->log_domain = g_strdup (log_domain);
385 domain->fatal_mask = G_LOG_FATAL_MASK;
386 domain->handlers = NULL;
388 domain->next = g_log_domains;
389 g_log_domains = domain;
391 return domain;
394 static void
395 g_log_domain_check_free_L (GLogDomain *domain)
397 if (domain->fatal_mask == G_LOG_FATAL_MASK &&
398 domain->handlers == NULL)
400 GLogDomain *last, *work;
402 last = NULL;
404 work = g_log_domains;
405 while (work)
407 if (work == domain)
409 if (last)
410 last->next = domain->next;
411 else
412 g_log_domains = domain->next;
413 g_free (domain->log_domain);
414 g_free (domain);
415 break;
417 last = work;
418 work = last->next;
423 static GLogFunc
424 g_log_domain_get_handler_L (GLogDomain *domain,
425 GLogLevelFlags log_level,
426 gpointer *data)
428 if (domain && log_level)
430 GLogHandler *handler;
432 handler = domain->handlers;
433 while (handler)
435 if ((handler->log_level & log_level) == log_level)
437 *data = handler->data;
438 return handler->log_func;
440 handler = handler->next;
444 *data = default_log_data;
445 return default_log_func;
449 * g_log_set_always_fatal:
450 * @fatal_mask: the mask containing bits set for each level
451 * of error which is to be fatal
453 * Sets the message levels which are always fatal, in any log domain.
454 * When a message with any of these levels is logged the program terminates.
455 * You can only set the levels defined by GLib to be fatal.
456 * %G_LOG_LEVEL_ERROR is always fatal.
458 * You can also make some message levels fatal at runtime by setting
459 * the `G_DEBUG` environment variable (see
460 * [Running GLib Applications](glib-running.html)).
462 * Returns: the old fatal mask
464 GLogLevelFlags
465 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
467 GLogLevelFlags old_mask;
469 /* restrict the global mask to levels that are known to glib
470 * since this setting applies to all domains
472 fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
473 /* force errors to be fatal */
474 fatal_mask |= G_LOG_LEVEL_ERROR;
475 /* remove bogus flag */
476 fatal_mask &= ~G_LOG_FLAG_FATAL;
478 g_mutex_lock (&g_messages_lock);
479 old_mask = g_log_always_fatal;
480 g_log_always_fatal = fatal_mask;
481 g_mutex_unlock (&g_messages_lock);
483 return old_mask;
487 * g_log_set_fatal_mask:
488 * @log_domain: the log domain
489 * @fatal_mask: the new fatal mask
491 * Sets the log levels which are fatal in the given domain.
492 * %G_LOG_LEVEL_ERROR is always fatal.
494 * Returns: the old fatal mask for the log domain
496 GLogLevelFlags
497 g_log_set_fatal_mask (const gchar *log_domain,
498 GLogLevelFlags fatal_mask)
500 GLogLevelFlags old_flags;
501 GLogDomain *domain;
503 if (!log_domain)
504 log_domain = "";
506 /* force errors to be fatal */
507 fatal_mask |= G_LOG_LEVEL_ERROR;
508 /* remove bogus flag */
509 fatal_mask &= ~G_LOG_FLAG_FATAL;
511 g_mutex_lock (&g_messages_lock);
513 domain = g_log_find_domain_L (log_domain);
514 if (!domain)
515 domain = g_log_domain_new_L (log_domain);
516 old_flags = domain->fatal_mask;
518 domain->fatal_mask = fatal_mask;
519 g_log_domain_check_free_L (domain);
521 g_mutex_unlock (&g_messages_lock);
523 return old_flags;
527 * g_log_set_handler:
528 * @log_domain: (allow-none): the log domain, or %NULL for the default ""
529 * application domain
530 * @log_levels: the log levels to apply the log handler for.
531 * To handle fatal and recursive messages as well, combine
532 * the log levels with the #G_LOG_FLAG_FATAL and
533 * #G_LOG_FLAG_RECURSION bit flags.
534 * @log_func: the log handler function
535 * @user_data: data passed to the log handler
537 * Sets the log handler for a domain and a set of log levels.
538 * To handle fatal and recursive messages the @log_levels parameter
539 * must be combined with the #G_LOG_FLAG_FATAL and #G_LOG_FLAG_RECURSION
540 * bit flags.
542 * Note that since the #G_LOG_LEVEL_ERROR log level is always fatal, if
543 * you want to set a handler for this log level you must combine it with
544 * #G_LOG_FLAG_FATAL.
546 * Here is an example for adding a log handler for all warning messages
547 * in the default domain:
548 * |[<!-- language="C" -->
549 * g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
550 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
551 * ]|
553 * This example adds a log handler for all critical messages from GTK+:
554 * |[<!-- language="C" -->
555 * g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
556 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
557 * ]|
559 * This example adds a log handler for all messages from GLib:
560 * |[<!-- language="C" -->
561 * g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
562 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
563 * ]|
565 * Returns: the id of the new handler
567 guint
568 g_log_set_handler (const gchar *log_domain,
569 GLogLevelFlags log_levels,
570 GLogFunc log_func,
571 gpointer user_data)
573 static guint handler_id = 0;
574 GLogDomain *domain;
575 GLogHandler *handler;
577 g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
578 g_return_val_if_fail (log_func != NULL, 0);
580 if (!log_domain)
581 log_domain = "";
583 handler = g_new (GLogHandler, 1);
585 g_mutex_lock (&g_messages_lock);
587 domain = g_log_find_domain_L (log_domain);
588 if (!domain)
589 domain = g_log_domain_new_L (log_domain);
591 handler->id = ++handler_id;
592 handler->log_level = log_levels;
593 handler->log_func = log_func;
594 handler->data = user_data;
595 handler->next = domain->handlers;
596 domain->handlers = handler;
598 g_mutex_unlock (&g_messages_lock);
600 return handler_id;
604 * g_log_set_default_handler:
605 * @log_func: the log handler function
606 * @user_data: data passed to the log handler
608 * Installs a default log handler which is used if no
609 * log handler has been set for the particular log domain
610 * and log level combination. By default, GLib uses
611 * g_log_default_handler() as default log handler.
613 * Returns: the previous default log handler
615 * Since: 2.6
617 GLogFunc
618 g_log_set_default_handler (GLogFunc log_func,
619 gpointer user_data)
621 GLogFunc old_log_func;
623 g_mutex_lock (&g_messages_lock);
624 old_log_func = default_log_func;
625 default_log_func = log_func;
626 default_log_data = user_data;
627 g_mutex_unlock (&g_messages_lock);
629 return old_log_func;
633 * g_test_log_set_fatal_handler:
634 * @log_func: the log handler function.
635 * @user_data: data passed to the log handler.
637 * Installs a non-error fatal log handler which can be
638 * used to decide whether log messages which are counted
639 * as fatal abort the program.
641 * The use case here is that you are running a test case
642 * that depends on particular libraries or circumstances
643 * and cannot prevent certain known critical or warning
644 * messages. So you install a handler that compares the
645 * domain and message to precisely not abort in such a case.
647 * Note that the handler is reset at the beginning of
648 * any test case, so you have to set it inside each test
649 * function which needs the special behavior.
651 * This handler has no effect on g_error messages.
653 * Since: 2.22
655 void
656 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
657 gpointer user_data)
659 g_mutex_lock (&g_messages_lock);
660 fatal_log_func = log_func;
661 fatal_log_data = user_data;
662 g_mutex_unlock (&g_messages_lock);
666 * g_log_remove_handler:
667 * @log_domain: the log domain
668 * @handler_id: the id of the handler, which was returned
669 * in g_log_set_handler()
671 * Removes the log handler.
673 void
674 g_log_remove_handler (const gchar *log_domain,
675 guint handler_id)
677 GLogDomain *domain;
679 g_return_if_fail (handler_id > 0);
681 if (!log_domain)
682 log_domain = "";
684 g_mutex_lock (&g_messages_lock);
685 domain = g_log_find_domain_L (log_domain);
686 if (domain)
688 GLogHandler *work, *last;
690 last = NULL;
691 work = domain->handlers;
692 while (work)
694 if (work->id == handler_id)
696 if (last)
697 last->next = work->next;
698 else
699 domain->handlers = work->next;
700 g_log_domain_check_free_L (domain);
701 g_mutex_unlock (&g_messages_lock);
702 g_free (work);
703 return;
705 last = work;
706 work = last->next;
709 g_mutex_unlock (&g_messages_lock);
710 g_warning ("%s: could not find handler with id '%d' for domain \"%s\"",
711 G_STRLOC, handler_id, log_domain);
714 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
715 (wc == 0x7f) || \
716 (wc >= 0x80 && wc < 0xa0)))
718 static gchar*
719 strdup_convert (const gchar *string,
720 const gchar *charset)
722 if (!g_utf8_validate (string, -1, NULL))
724 GString *gstring = g_string_new ("[Invalid UTF-8] ");
725 guchar *p;
727 for (p = (guchar *)string; *p; p++)
729 if (CHAR_IS_SAFE(*p) &&
730 !(*p == '\r' && *(p + 1) != '\n') &&
731 *p < 0x80)
732 g_string_append_c (gstring, *p);
733 else
734 g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
737 return g_string_free (gstring, FALSE);
739 else
741 GError *err = NULL;
743 gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
744 if (result)
745 return result;
746 else
748 /* Not thread-safe, but doesn't matter if we print the warning twice
750 static gboolean warned = FALSE;
751 if (!warned)
753 warned = TRUE;
754 _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
756 g_error_free (err);
758 return g_strdup (string);
763 /* For a radix of 8 we need at most 3 output bytes for 1 input
764 * byte. Additionally we might need up to 2 output bytes for the
765 * readix prefix and 1 byte for the trailing NULL.
767 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
769 static void
770 format_unsigned (gchar *buf,
771 gulong num,
772 guint radix)
774 gulong tmp;
775 gchar c;
776 gint i, n;
778 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
780 if (radix != 8 && radix != 10 && radix != 16)
782 *buf = '\000';
783 return;
786 if (!num)
788 *buf++ = '0';
789 *buf = '\000';
790 return;
793 if (radix == 16)
795 *buf++ = '0';
796 *buf++ = 'x';
798 else if (radix == 8)
800 *buf++ = '0';
803 n = 0;
804 tmp = num;
805 while (tmp)
807 tmp /= radix;
808 n++;
811 i = n;
813 /* Again we can't use g_assert; actually this check should _never_ fail. */
814 if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
816 *buf = '\000';
817 return;
820 while (num)
822 i--;
823 c = (num % radix);
824 if (c < 10)
825 buf[i] = c + '0';
826 else
827 buf[i] = c + 'a' - 10;
828 num /= radix;
831 buf[n] = '\000';
834 /* string size big enough to hold level prefix */
835 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
837 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
839 /* these are emitted by the default log handler */
840 #define DEFAULT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE)
841 /* these are filtered by G_MESSAGES_DEBUG by the default log handler */
842 #define INFO_LEVELS (G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG)
844 static int
845 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
846 GLogLevelFlags log_level)
848 gboolean to_stdout = TRUE;
850 /* we may not call _any_ GLib functions here */
852 switch (log_level & G_LOG_LEVEL_MASK)
854 case G_LOG_LEVEL_ERROR:
855 strcpy (level_prefix, "ERROR");
856 to_stdout = FALSE;
857 break;
858 case G_LOG_LEVEL_CRITICAL:
859 strcpy (level_prefix, "CRITICAL");
860 to_stdout = FALSE;
861 break;
862 case G_LOG_LEVEL_WARNING:
863 strcpy (level_prefix, "WARNING");
864 to_stdout = FALSE;
865 break;
866 case G_LOG_LEVEL_MESSAGE:
867 strcpy (level_prefix, "Message");
868 to_stdout = FALSE;
869 break;
870 case G_LOG_LEVEL_INFO:
871 strcpy (level_prefix, "INFO");
872 break;
873 case G_LOG_LEVEL_DEBUG:
874 strcpy (level_prefix, "DEBUG");
875 break;
876 default:
877 if (log_level)
879 strcpy (level_prefix, "LOG-");
880 format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
882 else
883 strcpy (level_prefix, "LOG");
884 break;
886 if (log_level & G_LOG_FLAG_RECURSION)
887 strcat (level_prefix, " (recursed)");
888 if (log_level & ALERT_LEVELS)
889 strcat (level_prefix, " **");
891 #ifdef G_OS_WIN32
892 if ((log_level & G_LOG_FLAG_FATAL) != 0 && !g_test_initialized ())
893 win32_keep_fatal_message = TRUE;
894 #endif
895 return to_stdout ? 1 : 2;
898 typedef struct {
899 gchar *log_domain;
900 GLogLevelFlags log_level;
901 gchar *pattern;
902 } GTestExpectedMessage;
904 static GSList *expected_messages = NULL;
907 * g_logv:
908 * @log_domain: the log domain
909 * @log_level: the log level
910 * @format: the message format. See the printf() documentation
911 * @args: the parameters to insert into the format string
913 * Logs an error or debugging message.
915 * If the log level has been set as fatal, the abort()
916 * function is called to terminate the program.
918 * If g_log_default_handler() is used as the log handler function, a new-line
919 * character will automatically be appended to @..., and need not be entered
920 * manually.
922 void
923 g_logv (const gchar *log_domain,
924 GLogLevelFlags log_level,
925 const gchar *format,
926 va_list args)
928 gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
929 gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
930 gchar buffer[1025], *msg, *msg_alloc = NULL;
931 gint i;
933 log_level &= G_LOG_LEVEL_MASK;
934 if (!log_level)
935 return;
937 if (log_level & G_LOG_FLAG_RECURSION)
939 /* we use a stack buffer of fixed size, since we're likely
940 * in an out-of-memory situation
942 gsize size G_GNUC_UNUSED;
944 size = _g_vsnprintf (buffer, 1024, format, args);
945 msg = buffer;
947 else
948 msg = msg_alloc = g_strdup_vprintf (format, args);
950 if (expected_messages)
952 GTestExpectedMessage *expected = expected_messages->data;
954 if (g_strcmp0 (expected->log_domain, log_domain) == 0 &&
955 ((log_level & expected->log_level) == expected->log_level) &&
956 g_pattern_match_simple (expected->pattern, msg))
958 expected_messages = g_slist_delete_link (expected_messages,
959 expected_messages);
960 g_free (expected->log_domain);
961 g_free (expected->pattern);
962 g_free (expected);
963 g_free (msg_alloc);
964 return;
966 else if ((log_level & G_LOG_LEVEL_DEBUG) != G_LOG_LEVEL_DEBUG)
968 gchar level_prefix[STRING_BUFFER_SIZE];
969 gchar *expected_message;
971 mklevel_prefix (level_prefix, expected->log_level);
972 expected_message = g_strdup_printf ("Did not see expected message %s-%s: %s",
973 expected->log_domain ? expected->log_domain : "**",
974 level_prefix, expected->pattern);
975 g_log_default_handler (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, expected_message, NULL);
976 g_free (expected_message);
978 log_level |= G_LOG_FLAG_FATAL;
982 for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
984 GLogLevelFlags test_level;
986 test_level = 1 << i;
987 if (log_level & test_level)
989 GLogDomain *domain;
990 GLogFunc log_func;
991 GLogLevelFlags domain_fatal_mask;
992 gpointer data = NULL;
993 gboolean masquerade_fatal = FALSE;
994 guint depth;
996 if (was_fatal)
997 test_level |= G_LOG_FLAG_FATAL;
998 if (was_recursion)
999 test_level |= G_LOG_FLAG_RECURSION;
1001 /* check recursion and lookup handler */
1002 g_mutex_lock (&g_messages_lock);
1003 depth = GPOINTER_TO_UINT (g_private_get (&g_log_depth));
1004 domain = g_log_find_domain_L (log_domain ? log_domain : "");
1005 if (depth)
1006 test_level |= G_LOG_FLAG_RECURSION;
1007 depth++;
1008 domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
1009 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
1010 test_level |= G_LOG_FLAG_FATAL;
1011 if (test_level & G_LOG_FLAG_RECURSION)
1012 log_func = _g_log_fallback_handler;
1013 else
1014 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
1015 domain = NULL;
1016 g_mutex_unlock (&g_messages_lock);
1018 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1020 log_func (log_domain, test_level, msg, data);
1022 if ((test_level & G_LOG_FLAG_FATAL)
1023 && !(test_level & G_LOG_LEVEL_ERROR))
1025 masquerade_fatal = fatal_log_func
1026 && !fatal_log_func (log_domain, test_level, msg, fatal_log_data);
1029 if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
1031 #ifdef G_OS_WIN32
1032 if (win32_keep_fatal_message)
1034 gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
1036 MessageBox (NULL, locale_msg, NULL,
1037 MB_ICONERROR|MB_SETFOREGROUND);
1039 _g_log_abort (IsDebuggerPresent () && !(test_level & G_LOG_FLAG_RECURSION));
1040 #else
1041 _g_log_abort (!(test_level & G_LOG_FLAG_RECURSION));
1042 #endif /* !G_OS_WIN32 */
1045 depth--;
1046 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1050 g_free (msg_alloc);
1054 * g_log:
1055 * @log_domain: the log domain, usually #G_LOG_DOMAIN
1056 * @log_level: the log level, either from #GLogLevelFlags
1057 * or a user-defined level
1058 * @format: the message format. See the printf() documentation
1059 * @...: the parameters to insert into the format string
1061 * Logs an error or debugging message.
1063 * If the log level has been set as fatal, the abort()
1064 * function is called to terminate the program.
1066 * If g_log_default_handler() is used as the log handler function, a new-line
1067 * character will automatically be appended to @..., and need not be entered
1068 * manually.
1070 void
1071 g_log (const gchar *log_domain,
1072 GLogLevelFlags log_level,
1073 const gchar *format,
1074 ...)
1076 va_list args;
1078 va_start (args, format);
1079 g_logv (log_domain, log_level, format, args);
1080 va_end (args);
1083 void
1084 g_return_if_fail_warning (const char *log_domain,
1085 const char *pretty_function,
1086 const char *expression)
1088 g_log (log_domain,
1089 G_LOG_LEVEL_CRITICAL,
1090 "%s: assertion '%s' failed",
1091 pretty_function,
1092 expression);
1095 void
1096 g_warn_message (const char *domain,
1097 const char *file,
1098 int line,
1099 const char *func,
1100 const char *warnexpr)
1102 char *s, lstr[32];
1103 g_snprintf (lstr, 32, "%d", line);
1104 if (warnexpr)
1105 s = g_strconcat ("(", file, ":", lstr, "):",
1106 func, func[0] ? ":" : "",
1107 " runtime check failed: (", warnexpr, ")", NULL);
1108 else
1109 s = g_strconcat ("(", file, ":", lstr, "):",
1110 func, func[0] ? ":" : "",
1111 " ", "code should not be reached", NULL);
1112 g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
1113 g_free (s);
1116 void
1117 g_assert_warning (const char *log_domain,
1118 const char *file,
1119 const int line,
1120 const char *pretty_function,
1121 const char *expression)
1123 if (expression)
1124 g_log (log_domain,
1125 G_LOG_LEVEL_ERROR,
1126 "file %s: line %d (%s): assertion failed: (%s)",
1127 file,
1128 line,
1129 pretty_function,
1130 expression);
1131 else
1132 g_log (log_domain,
1133 G_LOG_LEVEL_ERROR,
1134 "file %s: line %d (%s): should not be reached",
1135 file,
1136 line,
1137 pretty_function);
1138 _g_log_abort (FALSE);
1139 abort ();
1143 * g_test_expect_message:
1144 * @log_domain: (allow-none): the log domain of the message
1145 * @log_level: the log level of the message
1146 * @pattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
1148 * Indicates that a message with the given @log_domain and @log_level,
1149 * with text matching @pattern, is expected to be logged. When this
1150 * message is logged, it will not be printed, and the test case will
1151 * not abort.
1153 * Use g_test_assert_expected_messages() to assert that all
1154 * previously-expected messages have been seen and suppressed.
1156 * You can call this multiple times in a row, if multiple messages are
1157 * expected as a result of a single call. (The messages must appear in
1158 * the same order as the calls to g_test_expect_message().)
1160 * For example:
1162 * |[<!-- language="C" -->
1163 * // g_main_context_push_thread_default() should fail if the
1164 * // context is already owned by another thread.
1165 * g_test_expect_message (G_LOG_DOMAIN,
1166 * G_LOG_LEVEL_CRITICAL,
1167 * "assertion*acquired_context*failed");
1168 * g_main_context_push_thread_default (bad_context);
1169 * g_test_assert_expected_messages ();
1170 * ]|
1172 * Note that you cannot use this to test g_error() messages, since
1173 * g_error() intentionally never returns even if the program doesn't
1174 * abort; use g_test_trap_subprocess() in this case.
1176 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
1177 * expected via g_test_expect_message() then they will be ignored.
1179 * Since: 2.34
1181 void
1182 g_test_expect_message (const gchar *log_domain,
1183 GLogLevelFlags log_level,
1184 const gchar *pattern)
1186 GTestExpectedMessage *expected;
1188 g_return_if_fail (log_level != 0);
1189 g_return_if_fail (pattern != NULL);
1190 g_return_if_fail (~log_level & G_LOG_LEVEL_ERROR);
1192 expected = g_new (GTestExpectedMessage, 1);
1193 expected->log_domain = g_strdup (log_domain);
1194 expected->log_level = log_level;
1195 expected->pattern = g_strdup (pattern);
1197 expected_messages = g_slist_append (expected_messages, expected);
1200 void
1201 g_test_assert_expected_messages_internal (const char *domain,
1202 const char *file,
1203 int line,
1204 const char *func)
1206 if (expected_messages)
1208 GTestExpectedMessage *expected;
1209 gchar level_prefix[STRING_BUFFER_SIZE];
1210 gchar *message;
1212 expected = expected_messages->data;
1214 mklevel_prefix (level_prefix, expected->log_level);
1215 message = g_strdup_printf ("Did not see expected message %s-%s: %s",
1216 expected->log_domain ? expected->log_domain : "**",
1217 level_prefix, expected->pattern);
1218 g_assertion_message (G_LOG_DOMAIN, file, line, func, message);
1219 g_free (message);
1224 * g_test_assert_expected_messages:
1226 * Asserts that all messages previously indicated via
1227 * g_test_expect_message() have been seen and suppressed.
1229 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
1230 * expected via g_test_expect_message() then they will be ignored.
1232 * Since: 2.34
1235 void
1236 _g_log_fallback_handler (const gchar *log_domain,
1237 GLogLevelFlags log_level,
1238 const gchar *message,
1239 gpointer unused_data)
1241 gchar level_prefix[STRING_BUFFER_SIZE];
1242 #ifndef G_OS_WIN32
1243 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
1244 #endif
1245 int fd;
1247 /* we cannot call _any_ GLib functions in this fallback handler,
1248 * which is why we skip UTF-8 conversion, etc.
1249 * since we either recursed or ran out of memory, we're in a pretty
1250 * pathologic situation anyways, what we can do is giving the
1251 * the process ID unconditionally however.
1254 fd = mklevel_prefix (level_prefix, log_level);
1255 if (!message)
1256 message = "(NULL) message";
1258 #ifndef G_OS_WIN32
1259 format_unsigned (pid_string, getpid (), 10);
1260 #endif
1262 if (log_domain)
1263 write_string (fd, "\n");
1264 else
1265 write_string (fd, "\n** ");
1267 #ifndef G_OS_WIN32
1268 write_string (fd, "(process:");
1269 write_string (fd, pid_string);
1270 write_string (fd, "): ");
1271 #endif
1273 if (log_domain)
1275 write_string (fd, log_domain);
1276 write_string (fd, "-");
1278 write_string (fd, level_prefix);
1279 write_string (fd, ": ");
1280 write_string (fd, message);
1283 static void
1284 escape_string (GString *string)
1286 const char *p = string->str;
1287 gunichar wc;
1289 while (p < string->str + string->len)
1291 gboolean safe;
1293 wc = g_utf8_get_char_validated (p, -1);
1294 if (wc == (gunichar)-1 || wc == (gunichar)-2)
1296 gchar *tmp;
1297 guint pos;
1299 pos = p - string->str;
1301 /* Emit invalid UTF-8 as hex escapes
1303 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
1304 g_string_erase (string, pos, 1);
1305 g_string_insert (string, pos, tmp);
1307 p = string->str + (pos + 4); /* Skip over escape sequence */
1309 g_free (tmp);
1310 continue;
1312 if (wc == '\r')
1314 safe = *(p + 1) == '\n';
1316 else
1318 safe = CHAR_IS_SAFE (wc);
1321 if (!safe)
1323 gchar *tmp;
1324 guint pos;
1326 pos = p - string->str;
1328 /* Largest char we escape is 0x0a, so we don't have to worry
1329 * about 8-digit \Uxxxxyyyy
1331 tmp = g_strdup_printf ("\\u%04x", wc);
1332 g_string_erase (string, pos, g_utf8_next_char (p) - p);
1333 g_string_insert (string, pos, tmp);
1334 g_free (tmp);
1336 p = string->str + (pos + 6); /* Skip over escape sequence */
1338 else
1339 p = g_utf8_next_char (p);
1344 * g_log_default_handler:
1345 * @log_domain: the log domain of the message
1346 * @log_level: the level of the message
1347 * @message: the message
1348 * @unused_data: data passed from g_log() which is unused
1350 * The default log handler set up by GLib; g_log_set_default_handler()
1351 * allows to install an alternate default log handler.
1352 * This is used if no log handler has been set for the particular log
1353 * domain and log level combination. It outputs the message to stderr
1354 * or stdout and if the log level is fatal it calls abort(). It automatically
1355 * prints a new-line character after the message, so one does not need to be
1356 * manually included in @message.
1358 * The behavior of this log handler can be influenced by a number of
1359 * environment variables:
1361 * - `G_MESSAGES_PREFIXED`: A :-separated list of log levels for which
1362 * messages should be prefixed by the program name and PID of the
1363 * aplication.
1365 * - `G_MESSAGES_DEBUG`: A space-separated list of log domains for
1366 * which debug and informational messages are printed. By default
1367 * these messages are not printed.
1369 * stderr is used for levels %G_LOG_LEVEL_ERROR, %G_LOG_LEVEL_CRITICAL,
1370 * %G_LOG_LEVEL_WARNING and %G_LOG_LEVEL_MESSAGE. stdout is used for
1371 * the rest.
1373 void
1374 g_log_default_handler (const gchar *log_domain,
1375 GLogLevelFlags log_level,
1376 const gchar *message,
1377 gpointer unused_data)
1379 gchar level_prefix[STRING_BUFFER_SIZE], *string;
1380 GString *gstring;
1381 int fd;
1382 const gchar *domains;
1384 if ((log_level & DEFAULT_LEVELS) || (log_level >> G_LOG_LEVEL_USER_SHIFT))
1385 goto emit;
1387 domains = g_getenv ("G_MESSAGES_DEBUG");
1388 if (((log_level & INFO_LEVELS) == 0) ||
1389 domains == NULL ||
1390 (strcmp (domains, "all") != 0 && (!log_domain || !strstr (domains, log_domain))))
1391 return;
1393 emit:
1394 /* we can be called externally with recursion for whatever reason */
1395 if (log_level & G_LOG_FLAG_RECURSION)
1397 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
1398 return;
1401 fd = mklevel_prefix (level_prefix, log_level);
1403 gstring = g_string_new (NULL);
1404 if (log_level & ALERT_LEVELS)
1405 g_string_append (gstring, "\n");
1406 if (!log_domain)
1407 g_string_append (gstring, "** ");
1409 if ((g_log_msg_prefix & (log_level & G_LOG_LEVEL_MASK)) == (log_level & G_LOG_LEVEL_MASK))
1411 const gchar *prg_name = g_get_prgname ();
1413 if (!prg_name)
1414 g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
1415 else
1416 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
1419 if (log_domain)
1421 g_string_append (gstring, log_domain);
1422 g_string_append_c (gstring, '-');
1424 g_string_append (gstring, level_prefix);
1426 g_string_append (gstring, ": ");
1427 if (!message)
1428 g_string_append (gstring, "(NULL) message");
1429 else
1431 GString *msg;
1432 const gchar *charset;
1434 msg = g_string_new (message);
1435 escape_string (msg);
1437 if (g_get_charset (&charset))
1438 g_string_append (gstring, msg->str); /* charset is UTF-8 already */
1439 else
1441 string = strdup_convert (msg->str, charset);
1442 g_string_append (gstring, string);
1443 g_free (string);
1446 g_string_free (msg, TRUE);
1448 g_string_append (gstring, "\n");
1450 string = g_string_free (gstring, FALSE);
1452 write_string (fd, string);
1453 g_free (string);
1457 * g_set_print_handler:
1458 * @func: the new print handler
1460 * Sets the print handler.
1462 * Any messages passed to g_print() will be output via
1463 * the new handler. The default handler simply outputs
1464 * the message to stdout. By providing your own handler
1465 * you can redirect the output, to a GTK+ widget or a
1466 * log file for example.
1468 * Returns: the old print handler
1470 GPrintFunc
1471 g_set_print_handler (GPrintFunc func)
1473 GPrintFunc old_print_func;
1475 g_mutex_lock (&g_messages_lock);
1476 old_print_func = glib_print_func;
1477 glib_print_func = func;
1478 g_mutex_unlock (&g_messages_lock);
1480 return old_print_func;
1484 * g_print:
1485 * @format: the message format. See the printf() documentation
1486 * @...: the parameters to insert into the format string
1488 * Outputs a formatted message via the print handler.
1489 * The default print handler simply outputs the message to stdout, without
1490 * appending a trailing new-line character. Typically, @format should end with
1491 * its own new-line character.
1493 * g_print() should not be used from within libraries for debugging
1494 * messages, since it may be redirected by applications to special
1495 * purpose message windows or even files. Instead, libraries should
1496 * use g_log(), or the convenience functions g_message(), g_warning()
1497 * and g_error().
1499 void
1500 g_print (const gchar *format,
1501 ...)
1503 va_list args;
1504 gchar *string;
1505 GPrintFunc local_glib_print_func;
1507 g_return_if_fail (format != NULL);
1509 va_start (args, format);
1510 string = g_strdup_vprintf (format, args);
1511 va_end (args);
1513 g_mutex_lock (&g_messages_lock);
1514 local_glib_print_func = glib_print_func;
1515 g_mutex_unlock (&g_messages_lock);
1517 if (local_glib_print_func)
1518 local_glib_print_func (string);
1519 else
1521 const gchar *charset;
1523 if (g_get_charset (&charset))
1524 fputs (string, stdout); /* charset is UTF-8 already */
1525 else
1527 gchar *lstring = strdup_convert (string, charset);
1529 fputs (lstring, stdout);
1530 g_free (lstring);
1532 fflush (stdout);
1534 g_free (string);
1538 * g_set_printerr_handler:
1539 * @func: the new error message handler
1541 * Sets the handler for printing error messages.
1543 * Any messages passed to g_printerr() will be output via
1544 * the new handler. The default handler simply outputs the
1545 * message to stderr. By providing your own handler you can
1546 * redirect the output, to a GTK+ widget or a log file for
1547 * example.
1549 * Returns: the old error message handler
1551 GPrintFunc
1552 g_set_printerr_handler (GPrintFunc func)
1554 GPrintFunc old_printerr_func;
1556 g_mutex_lock (&g_messages_lock);
1557 old_printerr_func = glib_printerr_func;
1558 glib_printerr_func = func;
1559 g_mutex_unlock (&g_messages_lock);
1561 return old_printerr_func;
1565 * g_printerr:
1566 * @format: the message format. See the printf() documentation
1567 * @...: the parameters to insert into the format string
1569 * Outputs a formatted message via the error message handler.
1570 * The default handler simply outputs the message to stderr, without appending
1571 * a trailing new-line character. Typically, @format should end with its own
1572 * new-line character.
1574 * g_printerr() should not be used from within libraries.
1575 * Instead g_log() should be used, or the convenience functions
1576 * g_message(), g_warning() and g_error().
1578 void
1579 g_printerr (const gchar *format,
1580 ...)
1582 va_list args;
1583 gchar *string;
1584 GPrintFunc local_glib_printerr_func;
1586 g_return_if_fail (format != NULL);
1588 va_start (args, format);
1589 string = g_strdup_vprintf (format, args);
1590 va_end (args);
1592 g_mutex_lock (&g_messages_lock);
1593 local_glib_printerr_func = glib_printerr_func;
1594 g_mutex_unlock (&g_messages_lock);
1596 if (local_glib_printerr_func)
1597 local_glib_printerr_func (string);
1598 else
1600 const gchar *charset;
1602 if (g_get_charset (&charset))
1603 fputs (string, stderr); /* charset is UTF-8 already */
1604 else
1606 gchar *lstring = strdup_convert (string, charset);
1608 fputs (lstring, stderr);
1609 g_free (lstring);
1611 fflush (stderr);
1613 g_free (string);
1617 * g_printf_string_upper_bound:
1618 * @format: the format string. See the printf() documentation
1619 * @args: the parameters to be inserted into the format string
1621 * Calculates the maximum space needed to store the output
1622 * of the sprintf() function.
1624 * Returns: the maximum space needed to store the formatted string
1626 gsize
1627 g_printf_string_upper_bound (const gchar *format,
1628 va_list args)
1630 gchar c;
1631 return _g_vsnprintf (&c, 1, format, args) + 1;