docs: Fix GApplicationCommandLine typo
[glib.git] / glib / gmessages.c
blob7dafbf534186cf799b78f211aac507888182581e
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 "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"
76 #ifdef G_OS_WIN32
77 #include <process.h> /* For getpid() */
78 #include <io.h>
79 # define _WIN32_WINDOWS 0x0401 /* to get IsDebuggerPresent */
80 # include <windows.h>
81 #endif
84 /**
85 * SECTION:messages
86 * @title: Message Logging
87 * @short_description: versatile support for logging messages
88 * with different levels of importance
90 * These functions provide support for logging error messages
91 * or messages used for debugging.
93 * There are several built-in levels of messages, defined in
94 * #GLogLevelFlags. These can be extended with user-defined levels.
97 /**
98 * G_LOG_DOMAIN:
100 * Defines the log domain.
102 * For applications, this is typically left as the default %NULL
103 * (or "") domain. Libraries should define this so that any messages
104 * which they log can be differentiated from messages from other
105 * libraries and application code. But be careful not to define
106 * it in any public header files.
108 * For example, GTK+ uses this in its Makefile.am:
109 * |[
110 * INCLUDES = -DG_LOG_DOMAIN=\"Gtk\"
111 * ]|
115 * G_LOG_FATAL_MASK:
117 * GLib log levels that are considered fatal by default.
121 * GLogFunc:
122 * @log_domain: the log domain of the message
123 * @log_level: the log level of the message (including the
124 * fatal and recursion flags)
125 * @message: the message to process
126 * @user_data: user data, set in g_log_set_handler()
128 * Specifies the prototype of log handler functions.
132 * GLogLevelFlags:
133 * @G_LOG_FLAG_RECURSION: internal flag
134 * @G_LOG_FLAG_FATAL: internal flag
135 * @G_LOG_LEVEL_ERROR: log level for errors, see g_error().
136 * This level is also used for messages produced by g_assert().
137 * @G_LOG_LEVEL_CRITICAL: log level for critical messages, see g_critical().
138 * This level is also used for messages produced by g_return_if_fail()
139 * and g_return_val_if_fail().
140 * @G_LOG_LEVEL_WARNING: log level for warnings, see g_warning()
141 * @G_LOG_LEVEL_MESSAGE: log level for messages, see g_message()
142 * @G_LOG_LEVEL_INFO: log level for informational messages
143 * @G_LOG_LEVEL_DEBUG: log level for debug messages, see g_debug()
144 * @G_LOG_LEVEL_MASK: a mask including all log levels
146 * Flags specifying the level of log messages.
148 * It is possible to change how GLib treats messages of the various
149 * levels using g_log_set_handler() and g_log_set_fatal_mask().
153 * g_message:
154 * @...: format string, followed by parameters to insert
155 * into the format string (as with printf())
157 * A convenience function/macro to log a normal message.
161 * g_warning:
162 * @...: format string, followed by parameters to insert
163 * into the format string (as with printf())
165 * A convenience function/macro to log a warning message.
167 * You can make warnings fatal at runtime by setting the
168 * <envar>G_DEBUG</envar> environment variable (see
169 * <ulink url="glib-running.html">Running GLib Applications</ulink>).
173 * g_critical:
174 * @...: format string, followed by parameters to insert
175 * into the format string (as with printf())
177 * Logs a "critical warning" (#G_LOG_LEVEL_CRITICAL).
178 * It's more or less application-defined what constitutes
179 * a critical vs. a regular warning. You could call
180 * g_log_set_always_fatal() to make critical warnings exit
181 * the program, then use g_critical() for fatal errors, for
182 * example.
184 * You can also make critical warnings fatal at runtime by
185 * setting the <envar>G_DEBUG</envar> environment variable (see
186 * <ulink url="glib-running.html">Running GLib Applications</ulink>).
190 * g_error:
191 * @...: format string, followed by parameters to insert
192 * into the format string (as with printf())
194 * A convenience function/macro to log an error message.
196 * Error messages are always fatal, resulting in a call to
197 * abort() to terminate the application. This function will
198 * result in a core dump; don't use it for errors you expect.
199 * Using this function indicates a bug in your program, i.e.
200 * an assertion failure.
205 * g_debug:
206 * @...: format string, followed by parameters to insert
207 * into the format string (as with printf())
209 * A convenience function/macro to log a debug message.
211 * Since: 2.6
214 /* --- structures --- */
215 typedef struct _GLogDomain GLogDomain;
216 typedef struct _GLogHandler GLogHandler;
217 struct _GLogDomain
219 gchar *log_domain;
220 GLogLevelFlags fatal_mask;
221 GLogHandler *handlers;
222 GLogDomain *next;
224 struct _GLogHandler
226 guint id;
227 GLogLevelFlags log_level;
228 GLogFunc log_func;
229 gpointer data;
230 GLogHandler *next;
234 /* --- variables --- */
235 static GMutex g_messages_lock;
236 static GLogDomain *g_log_domains = NULL;
237 static GPrintFunc glib_print_func = NULL;
238 static GPrintFunc glib_printerr_func = NULL;
239 static GPrivate g_log_depth;
240 static GLogFunc default_log_func = g_log_default_handler;
241 static gpointer default_log_data = NULL;
242 static GTestLogFatalFunc fatal_log_func = NULL;
243 static gpointer fatal_log_data;
245 /* --- functions --- */
246 #ifdef G_OS_WIN32
247 # include <windows.h>
248 static gboolean win32_keep_fatal_message = FALSE;
250 /* This default message will usually be overwritten. */
251 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
252 * called with huge strings, is it?
254 static gchar fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
255 static gchar *fatal_msg_ptr = fatal_msg_buf;
257 #undef write
258 static inline int
259 dowrite (int fd,
260 const void *buf,
261 unsigned int len)
263 if (win32_keep_fatal_message)
265 memcpy (fatal_msg_ptr, buf, len);
266 fatal_msg_ptr += len;
267 *fatal_msg_ptr = 0;
268 return len;
271 write (fd, buf, len);
273 return len;
275 #define write(fd, buf, len) dowrite(fd, buf, len)
277 #endif
279 static void
280 write_string (int fd,
281 const gchar *string)
283 write (fd, string, strlen (string));
286 static GLogDomain*
287 g_log_find_domain_L (const gchar *log_domain)
289 register GLogDomain *domain;
291 domain = g_log_domains;
292 while (domain)
294 if (strcmp (domain->log_domain, log_domain) == 0)
295 return domain;
296 domain = domain->next;
298 return NULL;
301 static GLogDomain*
302 g_log_domain_new_L (const gchar *log_domain)
304 register GLogDomain *domain;
306 domain = g_new (GLogDomain, 1);
307 domain->log_domain = g_strdup (log_domain);
308 domain->fatal_mask = G_LOG_FATAL_MASK;
309 domain->handlers = NULL;
311 domain->next = g_log_domains;
312 g_log_domains = domain;
314 return domain;
317 static void
318 g_log_domain_check_free_L (GLogDomain *domain)
320 if (domain->fatal_mask == G_LOG_FATAL_MASK &&
321 domain->handlers == NULL)
323 register GLogDomain *last, *work;
325 last = NULL;
327 work = g_log_domains;
328 while (work)
330 if (work == domain)
332 if (last)
333 last->next = domain->next;
334 else
335 g_log_domains = domain->next;
336 g_free (domain->log_domain);
337 g_free (domain);
338 break;
340 last = work;
341 work = last->next;
346 static GLogFunc
347 g_log_domain_get_handler_L (GLogDomain *domain,
348 GLogLevelFlags log_level,
349 gpointer *data)
351 if (domain && log_level)
353 register GLogHandler *handler;
355 handler = domain->handlers;
356 while (handler)
358 if ((handler->log_level & log_level) == log_level)
360 *data = handler->data;
361 return handler->log_func;
363 handler = handler->next;
367 *data = default_log_data;
368 return default_log_func;
372 * g_log_set_always_fatal:
373 * @fatal_mask: the mask containing bits set for each level
374 * of error which is to be fatal
376 * Sets the message levels which are always fatal, in any log domain.
377 * When a message with any of these levels is logged the program terminates.
378 * You can only set the levels defined by GLib to be fatal.
379 * %G_LOG_LEVEL_ERROR is always fatal.
381 * You can also make some message levels fatal at runtime by setting
382 * the <envar>G_DEBUG</envar> environment variable (see
383 * <ulink url="glib-running.html">Running GLib Applications</ulink>).
385 * Returns: the old fatal mask
387 GLogLevelFlags
388 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
390 GLogLevelFlags old_mask;
392 /* restrict the global mask to levels that are known to glib
393 * since this setting applies to all domains
395 fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
396 /* force errors to be fatal */
397 fatal_mask |= G_LOG_LEVEL_ERROR;
398 /* remove bogus flag */
399 fatal_mask &= ~G_LOG_FLAG_FATAL;
401 g_mutex_lock (&g_messages_lock);
402 old_mask = g_log_always_fatal;
403 g_log_always_fatal = fatal_mask;
404 g_mutex_unlock (&g_messages_lock);
406 return old_mask;
410 * g_log_set_fatal_mask:
411 * @log_domain: the log domain
412 * @fatal_mask: the new fatal mask
414 * Sets the log levels which are fatal in the given domain.
415 * %G_LOG_LEVEL_ERROR is always fatal.
417 * Returns: the old fatal mask for the log domain
419 GLogLevelFlags
420 g_log_set_fatal_mask (const gchar *log_domain,
421 GLogLevelFlags fatal_mask)
423 GLogLevelFlags old_flags;
424 register GLogDomain *domain;
426 if (!log_domain)
427 log_domain = "";
429 /* force errors to be fatal */
430 fatal_mask |= G_LOG_LEVEL_ERROR;
431 /* remove bogus flag */
432 fatal_mask &= ~G_LOG_FLAG_FATAL;
434 g_mutex_lock (&g_messages_lock);
436 domain = g_log_find_domain_L (log_domain);
437 if (!domain)
438 domain = g_log_domain_new_L (log_domain);
439 old_flags = domain->fatal_mask;
441 domain->fatal_mask = fatal_mask;
442 g_log_domain_check_free_L (domain);
444 g_mutex_unlock (&g_messages_lock);
446 return old_flags;
450 * g_log_set_handler:
451 * @log_domain: the log domain, or %NULL for the default ""
452 * application domain
453 * @log_levels: the log levels to apply the log handler for.
454 * To handle fatal and recursive messages as well, combine
455 * the log levels with the #G_LOG_FLAG_FATAL and
456 * #G_LOG_FLAG_RECURSION bit flags.
457 * @log_func: the log handler function
458 * @user_data: data passed to the log handler
460 * Sets the log handler for a domain and a set of log levels.
461 * To handle fatal and recursive messages the @log_levels parameter
462 * must be combined with the #G_LOG_FLAG_FATAL and #G_LOG_FLAG_RECURSION
463 * bit flags.
465 * Note that since the #G_LOG_LEVEL_ERROR log level is always fatal, if
466 * you want to set a handler for this log level you must combine it with
467 * #G_LOG_FLAG_FATAL.
469 * <example>
470 * <title>Adding a log handler for all warning messages in the default
471 * (application) domain</title>
472 * <programlisting>
473 * g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
474 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
475 * </programlisting>
476 * </example>
478 * <example>
479 * <title>Adding a log handler for all critical messages from GTK+</title>
480 * <programlisting>
481 * g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
482 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
483 * </programlisting>
484 * </example>
486 * <example>
487 * <title>Adding a log handler for <emphasis>all</emphasis> messages from
488 * GLib</title>
489 * <programlisting>
490 * g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
491 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
492 * </programlisting>
493 * </example>
495 * Returns: the id of the new handler
497 guint
498 g_log_set_handler (const gchar *log_domain,
499 GLogLevelFlags log_levels,
500 GLogFunc log_func,
501 gpointer user_data)
503 static guint handler_id = 0;
504 GLogDomain *domain;
505 GLogHandler *handler;
507 g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
508 g_return_val_if_fail (log_func != NULL, 0);
510 if (!log_domain)
511 log_domain = "";
513 handler = g_new (GLogHandler, 1);
515 g_mutex_lock (&g_messages_lock);
517 domain = g_log_find_domain_L (log_domain);
518 if (!domain)
519 domain = g_log_domain_new_L (log_domain);
521 handler->id = ++handler_id;
522 handler->log_level = log_levels;
523 handler->log_func = log_func;
524 handler->data = user_data;
525 handler->next = domain->handlers;
526 domain->handlers = handler;
528 g_mutex_unlock (&g_messages_lock);
530 return handler_id;
534 * g_log_set_default_handler:
535 * @log_func: the log handler function
536 * @user_data: data passed to the log handler
538 * Installs a default log handler which is used if no
539 * log handler has been set for the particular log domain
540 * and log level combination. By default, GLib uses
541 * g_log_default_handler() as default log handler.
543 * Returns: the previous default log handler
545 * Since: 2.6
547 GLogFunc
548 g_log_set_default_handler (GLogFunc log_func,
549 gpointer user_data)
551 GLogFunc old_log_func;
553 g_mutex_lock (&g_messages_lock);
554 old_log_func = default_log_func;
555 default_log_func = log_func;
556 default_log_data = user_data;
557 g_mutex_unlock (&g_messages_lock);
559 return old_log_func;
563 * g_test_log_set_fatal_handler:
564 * @log_func: the log handler function.
565 * @user_data: data passed to the log handler.
567 * Installs a non-error fatal log handler which can be
568 * used to decide whether log messages which are counted
569 * as fatal abort the program.
571 * The use case here is that you are running a test case
572 * that depends on particular libraries or circumstances
573 * and cannot prevent certain known critical or warning
574 * messages. So you install a handler that compares the
575 * domain and message to precisely not abort in such a case.
577 * Note that the handler is reset at the beginning of
578 * any test case, so you have to set it inside each test
579 * function which needs the special behavior.
581 * This handler has no effect on g_error messages.
583 * Since: 2.22
585 void
586 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
587 gpointer user_data)
589 g_mutex_lock (&g_messages_lock);
590 fatal_log_func = log_func;
591 fatal_log_data = user_data;
592 g_mutex_unlock (&g_messages_lock);
596 * g_log_remove_handler:
597 * @log_domain: the log domain
598 * @handler_id: the id of the handler, which was returned
599 * in g_log_set_handler()
601 * Removes the log handler.
603 void
604 g_log_remove_handler (const gchar *log_domain,
605 guint handler_id)
607 register GLogDomain *domain;
609 g_return_if_fail (handler_id > 0);
611 if (!log_domain)
612 log_domain = "";
614 g_mutex_lock (&g_messages_lock);
615 domain = g_log_find_domain_L (log_domain);
616 if (domain)
618 GLogHandler *work, *last;
620 last = NULL;
621 work = domain->handlers;
622 while (work)
624 if (work->id == handler_id)
626 if (last)
627 last->next = work->next;
628 else
629 domain->handlers = work->next;
630 g_log_domain_check_free_L (domain);
631 g_mutex_unlock (&g_messages_lock);
632 g_free (work);
633 return;
635 last = work;
636 work = last->next;
639 g_mutex_unlock (&g_messages_lock);
640 g_warning ("%s: could not find handler with id `%d' for domain \"%s\"",
641 G_STRLOC, handler_id, log_domain);
645 * g_logv:
646 * @log_domain: the log domain
647 * @log_level: the log level
648 * @format: the message format. See the printf() documentation
649 * @args: the parameters to insert into the format string
651 * Logs an error or debugging message.
653 * If the log level has been set as fatal, the abort()
654 * function is called to terminate the program.
656 void
657 g_logv (const gchar *log_domain,
658 GLogLevelFlags log_level,
659 const gchar *format,
660 va_list args1)
662 gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
663 gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
664 gint i;
666 log_level &= G_LOG_LEVEL_MASK;
667 if (!log_level)
668 return;
670 for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
672 register GLogLevelFlags test_level;
674 test_level = 1 << i;
675 if (log_level & test_level)
677 GLogDomain *domain;
678 GLogFunc log_func;
679 GLogLevelFlags domain_fatal_mask;
680 gpointer data = NULL;
681 gboolean masquerade_fatal = FALSE;
682 guint depth;
684 if (was_fatal)
685 test_level |= G_LOG_FLAG_FATAL;
686 if (was_recursion)
687 test_level |= G_LOG_FLAG_RECURSION;
689 /* check recursion and lookup handler */
690 g_mutex_lock (&g_messages_lock);
691 depth = GPOINTER_TO_UINT (g_private_get (&g_log_depth));
692 domain = g_log_find_domain_L (log_domain ? log_domain : "");
693 if (depth)
694 test_level |= G_LOG_FLAG_RECURSION;
695 depth++;
696 domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
697 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
698 test_level |= G_LOG_FLAG_FATAL;
699 if (test_level & G_LOG_FLAG_RECURSION)
700 log_func = _g_log_fallback_handler;
701 else
702 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
703 domain = NULL;
704 g_mutex_unlock (&g_messages_lock);
706 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
709 if (test_level & G_LOG_FLAG_RECURSION)
711 /* we use a stack buffer of fixed size, since we're likely
712 * in an out-of-memory situation
714 gchar buffer[1025];
715 gsize size G_GNUC_UNUSED;
716 va_list args2;
718 G_VA_COPY (args2, args1);
719 size = _g_vsnprintf (buffer, 1024, format, args2);
720 va_end (args2);
722 log_func (log_domain, test_level, buffer, data);
724 else
726 gchar *msg;
727 va_list args2;
729 G_VA_COPY (args2, args1);
730 msg = g_strdup_vprintf (format, args2);
731 va_end (args2);
733 log_func (log_domain, test_level, msg, data);
735 if ((test_level & G_LOG_FLAG_FATAL)
736 && !(test_level & G_LOG_LEVEL_ERROR))
738 masquerade_fatal = fatal_log_func
739 && !fatal_log_func (log_domain, test_level, msg, fatal_log_data);
742 g_free (msg);
745 if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
747 #ifdef G_OS_WIN32
748 gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
750 MessageBox (NULL, locale_msg, NULL,
751 MB_ICONERROR|MB_SETFOREGROUND);
752 if (IsDebuggerPresent () && !(test_level & G_LOG_FLAG_RECURSION))
753 G_BREAKPOINT ();
754 else
755 abort ();
756 #else
757 if (!(test_level & G_LOG_FLAG_RECURSION))
758 G_BREAKPOINT ();
759 else
760 abort ();
761 #endif /* !G_OS_WIN32 */
764 depth--;
765 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
771 * g_log:
772 * @log_domain: the log domain, usually #G_LOG_DOMAIN
773 * @log_level: the log level, either from #GLogLevelFlags
774 * or a user-defined level
775 * @format: the message format. See the printf() documentation
776 * @...: the parameters to insert into the format string
778 * Logs an error or debugging message.
780 * If the log level has been set as fatal, the abort()
781 * function is called to terminate the program.
783 void
784 g_log (const gchar *log_domain,
785 GLogLevelFlags log_level,
786 const gchar *format,
787 ...)
789 va_list args;
791 va_start (args, format);
792 g_logv (log_domain, log_level, format, args);
793 va_end (args);
796 void
797 g_return_if_fail_warning (const char *log_domain,
798 const char *pretty_function,
799 const char *expression)
801 g_log (log_domain,
802 G_LOG_LEVEL_CRITICAL,
803 "%s: assertion `%s' failed",
804 pretty_function,
805 expression);
808 void
809 g_warn_message (const char *domain,
810 const char *file,
811 int line,
812 const char *func,
813 const char *warnexpr)
815 char *s, lstr[32];
816 g_snprintf (lstr, 32, "%d", line);
817 if (warnexpr)
818 s = g_strconcat ("(", file, ":", lstr, "):",
819 func, func[0] ? ":" : "",
820 " runtime check failed: (", warnexpr, ")", NULL);
821 else
822 s = g_strconcat ("(", file, ":", lstr, "):",
823 func, func[0] ? ":" : "",
824 " ", "code should not be reached", NULL);
825 g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
826 g_free (s);
829 void
830 g_assert_warning (const char *log_domain,
831 const char *file,
832 const int line,
833 const char *pretty_function,
834 const char *expression)
836 g_log (log_domain,
837 G_LOG_LEVEL_ERROR,
838 expression
839 ? "file %s: line %d (%s): assertion failed: (%s)"
840 : "file %s: line %d (%s): should not be reached",
841 file,
842 line,
843 pretty_function,
844 expression);
845 abort ();
848 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
849 (wc == 0x7f) || \
850 (wc >= 0x80 && wc < 0xa0)))
852 static gchar*
853 strdup_convert (const gchar *string,
854 const gchar *charset)
856 if (!g_utf8_validate (string, -1, NULL))
858 GString *gstring = g_string_new ("[Invalid UTF-8] ");
859 guchar *p;
861 for (p = (guchar *)string; *p; p++)
863 if (CHAR_IS_SAFE(*p) &&
864 !(*p == '\r' && *(p + 1) != '\n') &&
865 *p < 0x80)
866 g_string_append_c (gstring, *p);
867 else
868 g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
871 return g_string_free (gstring, FALSE);
873 else
875 GError *err = NULL;
877 gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
878 if (result)
879 return result;
880 else
882 /* Not thread-safe, but doesn't matter if we print the warning twice
884 static gboolean warned = FALSE;
885 if (!warned)
887 warned = TRUE;
888 _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
890 g_error_free (err);
892 return g_strdup (string);
897 /* For a radix of 8 we need at most 3 output bytes for 1 input
898 * byte. Additionally we might need up to 2 output bytes for the
899 * readix prefix and 1 byte for the trailing NULL.
901 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
903 static void
904 format_unsigned (gchar *buf,
905 gulong num,
906 guint radix)
908 gulong tmp;
909 gchar c;
910 gint i, n;
912 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
914 if (radix != 8 && radix != 10 && radix != 16)
916 *buf = '\000';
917 return;
920 if (!num)
922 *buf++ = '0';
923 *buf = '\000';
924 return;
927 if (radix == 16)
929 *buf++ = '0';
930 *buf++ = 'x';
932 else if (radix == 8)
934 *buf++ = '0';
937 n = 0;
938 tmp = num;
939 while (tmp)
941 tmp /= radix;
942 n++;
945 i = n;
947 /* Again we can't use g_assert; actually this check should _never_ fail. */
948 if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
950 *buf = '\000';
951 return;
954 while (num)
956 i--;
957 c = (num % radix);
958 if (c < 10)
959 buf[i] = c + '0';
960 else
961 buf[i] = c + 'a' - 10;
962 num /= radix;
965 buf[n] = '\000';
968 /* string size big enough to hold level prefix */
969 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
971 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
973 /* these are emitted by the default log handler */
974 #define DEFAULT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE)
975 /* these are filtered by G_MESSAGES_DEBUG by the default log handler */
976 #define INFO_LEVELS (G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG)
978 static int
979 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
980 GLogLevelFlags log_level)
982 gboolean to_stdout = TRUE;
984 /* we may not call _any_ GLib functions here */
986 switch (log_level & G_LOG_LEVEL_MASK)
988 case G_LOG_LEVEL_ERROR:
989 strcpy (level_prefix, "ERROR");
990 to_stdout = FALSE;
991 break;
992 case G_LOG_LEVEL_CRITICAL:
993 strcpy (level_prefix, "CRITICAL");
994 to_stdout = FALSE;
995 break;
996 case G_LOG_LEVEL_WARNING:
997 strcpy (level_prefix, "WARNING");
998 to_stdout = FALSE;
999 break;
1000 case G_LOG_LEVEL_MESSAGE:
1001 strcpy (level_prefix, "Message");
1002 to_stdout = FALSE;
1003 break;
1004 case G_LOG_LEVEL_INFO:
1005 strcpy (level_prefix, "INFO");
1006 break;
1007 case G_LOG_LEVEL_DEBUG:
1008 strcpy (level_prefix, "DEBUG");
1009 break;
1010 default:
1011 if (log_level)
1013 strcpy (level_prefix, "LOG-");
1014 format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
1016 else
1017 strcpy (level_prefix, "LOG");
1018 break;
1020 if (log_level & G_LOG_FLAG_RECURSION)
1021 strcat (level_prefix, " (recursed)");
1022 if (log_level & ALERT_LEVELS)
1023 strcat (level_prefix, " **");
1025 #ifdef G_OS_WIN32
1026 win32_keep_fatal_message = (log_level & G_LOG_FLAG_FATAL) != 0;
1027 #endif
1028 return to_stdout ? 1 : 2;
1031 void
1032 _g_log_fallback_handler (const gchar *log_domain,
1033 GLogLevelFlags log_level,
1034 const gchar *message,
1035 gpointer unused_data)
1037 gchar level_prefix[STRING_BUFFER_SIZE];
1038 #ifndef G_OS_WIN32
1039 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
1040 #endif
1041 int fd;
1043 /* we cannot call _any_ GLib functions in this fallback handler,
1044 * which is why we skip UTF-8 conversion, etc.
1045 * since we either recursed or ran out of memory, we're in a pretty
1046 * pathologic situation anyways, what we can do is giving the
1047 * the process ID unconditionally however.
1050 fd = mklevel_prefix (level_prefix, log_level);
1051 if (!message)
1052 message = "(NULL) message";
1054 #ifndef G_OS_WIN32
1055 format_unsigned (pid_string, getpid (), 10);
1056 #endif
1058 if (log_domain)
1059 write_string (fd, "\n");
1060 else
1061 write_string (fd, "\n** ");
1063 #ifndef G_OS_WIN32
1064 write_string (fd, "(process:");
1065 write_string (fd, pid_string);
1066 write_string (fd, "): ");
1067 #endif
1069 if (log_domain)
1071 write_string (fd, log_domain);
1072 write_string (fd, "-");
1074 write_string (fd, level_prefix);
1075 write_string (fd, ": ");
1076 write_string (fd, message);
1079 static void
1080 escape_string (GString *string)
1082 const char *p = string->str;
1083 gunichar wc;
1085 while (p < string->str + string->len)
1087 gboolean safe;
1089 wc = g_utf8_get_char_validated (p, -1);
1090 if (wc == (gunichar)-1 || wc == (gunichar)-2)
1092 gchar *tmp;
1093 guint pos;
1095 pos = p - string->str;
1097 /* Emit invalid UTF-8 as hex escapes
1099 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
1100 g_string_erase (string, pos, 1);
1101 g_string_insert (string, pos, tmp);
1103 p = string->str + (pos + 4); /* Skip over escape sequence */
1105 g_free (tmp);
1106 continue;
1108 if (wc == '\r')
1110 safe = *(p + 1) == '\n';
1112 else
1114 safe = CHAR_IS_SAFE (wc);
1117 if (!safe)
1119 gchar *tmp;
1120 guint pos;
1122 pos = p - string->str;
1124 /* Largest char we escape is 0x0a, so we don't have to worry
1125 * about 8-digit \Uxxxxyyyy
1127 tmp = g_strdup_printf ("\\u%04x", wc);
1128 g_string_erase (string, pos, g_utf8_next_char (p) - p);
1129 g_string_insert (string, pos, tmp);
1130 g_free (tmp);
1132 p = string->str + (pos + 6); /* Skip over escape sequence */
1134 else
1135 p = g_utf8_next_char (p);
1140 * g_log_default_handler:
1141 * @log_domain: the log domain of the message
1142 * @log_level: the level of the message
1143 * @message: the message
1144 * @unused_data: data passed from g_log() which is unused
1146 * The default log handler set up by GLib; g_log_set_default_handler()
1147 * allows to install an alternate default log handler.
1148 * This is used if no log handler has been set for the particular log
1149 * domain and log level combination. It outputs the message to stderr
1150 * or stdout and if the log level is fatal it calls abort().
1152 * The behavior of this log handler can be influenced by a number of
1153 * environment variables:
1154 * <variablelist>
1155 * <varlistentry>
1156 * <term><envar>G_MESSAGES_PREFIXED</envar></term>
1157 * <listitem>
1158 * A :-separated list of log levels for which messages should
1159 * be prefixed by the program name and PID of the aplication.
1160 * </listitem>
1161 * </varlistentry>
1162 * <varlistentry>
1163 * <term><envar>G_MESSAGES_DEBUG</envar></term>
1164 * <listitem>
1165 * A space-separated list of log domains for which debug and
1166 * informational messages are printed. By default these
1167 * messages are not printed.
1168 * </listitem>
1169 * </varlistentry>
1170 * </variablelist>
1172 * stderr is used for levels %G_LOG_LEVEL_ERROR, %G_LOG_LEVEL_CRITICAL,
1173 * %G_LOG_LEVEL_WARNING and %G_LOG_LEVEL_MESSAGE. stdout is used for
1174 * the rest.
1176 void
1177 g_log_default_handler (const gchar *log_domain,
1178 GLogLevelFlags log_level,
1179 const gchar *message,
1180 gpointer unused_data)
1182 gchar level_prefix[STRING_BUFFER_SIZE], *string;
1183 GString *gstring;
1184 int fd;
1185 const gchar *domains;
1187 if ((log_level & DEFAULT_LEVELS) || (log_level >> G_LOG_LEVEL_USER_SHIFT))
1188 goto emit;
1190 domains = g_getenv ("G_MESSAGES_DEBUG");
1191 if (((log_level & INFO_LEVELS) == 0) ||
1192 domains == NULL ||
1193 (strcmp (domains, "all") != 0 && (!log_domain || !strstr (domains, log_domain))))
1194 return;
1196 emit:
1197 /* we can be called externally with recursion for whatever reason */
1198 if (log_level & G_LOG_FLAG_RECURSION)
1200 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
1201 return;
1204 fd = mklevel_prefix (level_prefix, log_level);
1206 gstring = g_string_new (NULL);
1207 if (log_level & ALERT_LEVELS)
1208 g_string_append (gstring, "\n");
1209 if (!log_domain)
1210 g_string_append (gstring, "** ");
1212 if ((g_log_msg_prefix & log_level) == log_level)
1214 const gchar *prg_name = g_get_prgname ();
1216 if (!prg_name)
1217 g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
1218 else
1219 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
1222 if (log_domain)
1224 g_string_append (gstring, log_domain);
1225 g_string_append_c (gstring, '-');
1227 g_string_append (gstring, level_prefix);
1229 g_string_append (gstring, ": ");
1230 if (!message)
1231 g_string_append (gstring, "(NULL) message");
1232 else
1234 GString *msg;
1235 const gchar *charset;
1237 msg = g_string_new (message);
1238 escape_string (msg);
1240 if (g_get_charset (&charset))
1241 g_string_append (gstring, msg->str); /* charset is UTF-8 already */
1242 else
1244 string = strdup_convert (msg->str, charset);
1245 g_string_append (gstring, string);
1246 g_free (string);
1249 g_string_free (msg, TRUE);
1251 g_string_append (gstring, "\n");
1253 string = g_string_free (gstring, FALSE);
1255 write_string (fd, string);
1256 g_free (string);
1260 * g_set_print_handler:
1261 * @func: the new print handler
1263 * Sets the print handler.
1265 * Any messages passed to g_print() will be output via
1266 * the new handler. The default handler simply outputs
1267 * the message to stdout. By providing your own handler
1268 * you can redirect the output, to a GTK+ widget or a
1269 * log file for example.
1271 * Returns: the old print handler
1273 GPrintFunc
1274 g_set_print_handler (GPrintFunc func)
1276 GPrintFunc old_print_func;
1278 g_mutex_lock (&g_messages_lock);
1279 old_print_func = glib_print_func;
1280 glib_print_func = func;
1281 g_mutex_unlock (&g_messages_lock);
1283 return old_print_func;
1287 * g_print:
1288 * @format: the message format. See the printf() documentation
1289 * @...: the parameters to insert into the format string
1291 * Outputs a formatted message via the print handler.
1292 * The default print handler simply outputs the message to stdout.
1294 * g_print() should not be used from within libraries for debugging
1295 * messages, since it may be redirected by applications to special
1296 * purpose message windows or even files. Instead, libraries should
1297 * use g_log(), or the convenience functions g_message(), g_warning()
1298 * and g_error().
1300 void
1301 g_print (const gchar *format,
1302 ...)
1304 va_list args;
1305 gchar *string;
1306 GPrintFunc local_glib_print_func;
1308 g_return_if_fail (format != NULL);
1310 va_start (args, format);
1311 string = g_strdup_vprintf (format, args);
1312 va_end (args);
1314 g_mutex_lock (&g_messages_lock);
1315 local_glib_print_func = glib_print_func;
1316 g_mutex_unlock (&g_messages_lock);
1318 if (local_glib_print_func)
1319 local_glib_print_func (string);
1320 else
1322 const gchar *charset;
1324 if (g_get_charset (&charset))
1325 fputs (string, stdout); /* charset is UTF-8 already */
1326 else
1328 gchar *lstring = strdup_convert (string, charset);
1330 fputs (lstring, stdout);
1331 g_free (lstring);
1333 fflush (stdout);
1335 g_free (string);
1339 * g_set_printerr_handler:
1340 * @func: the new error message handler
1342 * Sets the handler for printing error messages.
1344 * Any messages passed to g_printerr() will be output via
1345 * the new handler. The default handler simply outputs the
1346 * message to stderr. By providing your own handler you can
1347 * redirect the output, to a GTK+ widget or a log file for
1348 * example.
1350 * Returns: the old error message handler
1352 GPrintFunc
1353 g_set_printerr_handler (GPrintFunc func)
1355 GPrintFunc old_printerr_func;
1357 g_mutex_lock (&g_messages_lock);
1358 old_printerr_func = glib_printerr_func;
1359 glib_printerr_func = func;
1360 g_mutex_unlock (&g_messages_lock);
1362 return old_printerr_func;
1366 * g_printerr:
1367 * @format: the message format. See the printf() documentation
1368 * @...: the parameters to insert into the format string
1370 * Outputs a formatted message via the error message handler.
1371 * The default handler simply outputs the message to stderr.
1373 * g_printerr() should not be used from within libraries.
1374 * Instead g_log() should be used, or the convenience functions
1375 * g_message(), g_warning() and g_error().
1377 void
1378 g_printerr (const gchar *format,
1379 ...)
1381 va_list args;
1382 gchar *string;
1383 GPrintFunc local_glib_printerr_func;
1385 g_return_if_fail (format != NULL);
1387 va_start (args, format);
1388 string = g_strdup_vprintf (format, args);
1389 va_end (args);
1391 g_mutex_lock (&g_messages_lock);
1392 local_glib_printerr_func = glib_printerr_func;
1393 g_mutex_unlock (&g_messages_lock);
1395 if (local_glib_printerr_func)
1396 local_glib_printerr_func (string);
1397 else
1399 const gchar *charset;
1401 if (g_get_charset (&charset))
1402 fputs (string, stderr); /* charset is UTF-8 already */
1403 else
1405 gchar *lstring = strdup_convert (string, charset);
1407 fputs (lstring, stderr);
1408 g_free (lstring);
1410 fflush (stderr);
1412 g_free (string);
1416 * g_printf_string_upper_bound:
1417 * @format: the format string. See the printf() documentation
1418 * @args: the parameters to be inserted into the format string
1420 * Calculates the maximum space needed to store the output
1421 * of the sprintf() function.
1423 * Returns: the maximum space needed to store the formatted string
1425 gsize
1426 g_printf_string_upper_bound (const gchar *format,
1427 va_list args)
1429 gchar c;
1430 return _g_vsnprintf (&c, 1, format, args) + 1;