3edb67c8ab288ec3f42301f4c0cea04dc4211592
[platform/upstream/glib.git] / glib / gmessages.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
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.
8  *
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.
13  *
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.
18  */
19
20 /*
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/.
25  */
26
27 /*
28  * MT safe
29  */
30
31 /**
32  * SECTION:warnings
33  * @Title: Message Output and Debugging Functions
34  * @Short_description: functions to output messages and help debug applications
35  *
36  * These functions provide support for outputting messages.
37  *
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.
47  */
48
49 #include "config.h"
50
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>
61
62 #include "gmessages.h"
63
64 #include "glib-init.h"
65 #include "gbacktrace.h"
66 #include "gcharset.h"
67 #include "gconvert.h"
68 #include "gmem.h"
69 #include "gprintfint.h"
70 #include "gtestutils.h"
71 #include "gthread.h"
72 #include "gstrfuncs.h"
73 #include "gstring.h"
74
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
81
82
83 /**
84  * SECTION:messages
85  * @title: Message Logging
86  * @short_description: versatile support for logging messages
87  *     with different levels of importance
88  *
89  * These functions provide support for logging error messages
90  * or messages used for debugging.
91  *
92  * There are several built-in levels of messages, defined in
93  * #GLogLevelFlags. These can be extended with user-defined levels.
94  */
95
96 /**
97  * G_LOG_DOMAIN:
98  *
99  * Defines the log domain.
100  *
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.
106  *
107  * For example, GTK+ uses this in its Makefile.am:
108  * |[
109  * INCLUDES = -DG_LOG_DOMAIN=\"Gtk\"
110  * ]|
111  */
112
113 /**
114  * G_LOG_FATAL_MASK:
115  *
116  * GLib log levels that are considered fatal by default.
117  */
118
119 /**
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()
126  *
127  * Specifies the prototype of log handler functions.
128  */
129
130 /**
131  * GLogLevelFlags:
132  * @G_LOG_FLAG_RECURSION: internal flag
133  * @G_LOG_FLAG_FATAL: internal flag
134  * @G_LOG_LEVEL_ERROR: log level for errors, see g_error().
135  *     This level is also used for messages produced by g_assert().
136  * @G_LOG_LEVEL_CRITICAL: log level for critical messages, see g_critical().
137  *     This level is also used for messages produced by g_return_if_fail()
138  *     and g_return_val_if_fail().
139  * @G_LOG_LEVEL_WARNING: log level for warnings, see g_warning()
140  * @G_LOG_LEVEL_MESSAGE: log level for messages, see g_message()
141  * @G_LOG_LEVEL_INFO: log level for informational messages
142  * @G_LOG_LEVEL_DEBUG: log level for debug messages, see g_debug()
143  * @G_LOG_LEVEL_MASK: a mask including all log levels
144  *
145  * Flags specifying the level of log messages.
146  *
147  * It is possible to change how GLib treats messages of the various
148  * levels using g_log_set_handler() and g_log_set_fatal_mask().
149  */
150
151 /**
152  * g_message:
153  * @...: format string, followed by parameters to insert
154  *     into the format string (as with printf())
155  *
156  * A convenience function/macro to log a normal message.
157  */
158
159 /**
160  * g_warning:
161  * @...: format string, followed by parameters to insert
162  *     into the format string (as with printf())
163  *
164  * A convenience function/macro to log a warning message.
165  *
166  * You can make warnings fatal at runtime by setting the
167  * %G_DEBUG environment variable (see
168  * <ulink url="glib-running.html">Running GLib Applications</ulink>).
169  */
170
171 /**
172  * g_critical:
173  * @...: format string, followed by parameters to insert
174  *     into the format string (as with printf())
175  *
176  * Logs a "critical warning" (#G_LOG_LEVEL_CRITICAL).
177  * It's more or less application-defined what constitutes
178  * a critical vs. a regular warning. You could call
179  * g_log_set_always_fatal() to make critical warnings exit
180  * the program, then use g_critical() for fatal errors, for
181  * example.
182  *
183  * You can also make critical warnings fatal at runtime by
184  * setting the %G_DEBUG environment variable (see
185  * <ulink url="glib-running.html">Running GLib Applications</ulink>).
186  */
187
188 /**
189  * g_error:
190  * @...: format string, followed by parameters to insert
191  *     into the format string (as with printf())
192  *
193  * A convenience function/macro to log an error message.
194  *
195  * Error messages are always fatal, resulting in a call to
196  * abort() to terminate the application. This function will
197  * result in a core dump; don't use it for errors you expect.
198  * Using this function indicates a bug in your program, i.e.
199  * an assertion failure.
200  *
201  */
202
203 /**
204  * g_debug:
205  * @...: format string, followed by parameters to insert
206  *     into the format string (as with printf())
207  *
208  * A convenience function/macro to log a debug message.
209  *
210  * Since: 2.6
211  */
212
213 /* --- structures --- */
214 typedef struct _GLogDomain      GLogDomain;
215 typedef struct _GLogHandler     GLogHandler;
216 struct _GLogDomain
217 {
218   gchar         *log_domain;
219   GLogLevelFlags fatal_mask;
220   GLogHandler   *handlers;
221   GLogDomain    *next;
222 };
223 struct _GLogHandler
224 {
225   guint          id;
226   GLogLevelFlags log_level;
227   GLogFunc       log_func;
228   gpointer       data;
229   GLogHandler   *next;
230 };
231
232
233 /* --- variables --- */
234 static GMutex         g_messages_lock;
235 static GLogDomain    *g_log_domains = NULL;
236 static GPrintFunc     glib_print_func = NULL;
237 static GPrintFunc     glib_printerr_func = NULL;
238 static GPrivate       g_log_depth;
239 static GLogFunc       default_log_func = g_log_default_handler;
240 static gpointer       default_log_data = NULL;
241 static GTestLogFatalFunc fatal_log_func = NULL;
242 static gpointer          fatal_log_data;
243
244 /* --- functions --- */
245 #ifdef G_OS_WIN32
246 #  include <windows.h>
247 static gboolean win32_keep_fatal_message = FALSE;
248
249 /* This default message will usually be overwritten. */
250 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
251  * called with huge strings, is it?
252  */
253 static gchar  fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
254 static gchar *fatal_msg_ptr = fatal_msg_buf;
255
256 #undef write
257 static inline int
258 dowrite (int          fd,
259          const void  *buf,
260          unsigned int len)
261 {
262   if (win32_keep_fatal_message)
263     {
264       memcpy (fatal_msg_ptr, buf, len);
265       fatal_msg_ptr += len;
266       *fatal_msg_ptr = 0;
267       return len;
268     }
269
270   write (fd, buf, len);
271
272   return len;
273 }
274 #define write(fd, buf, len) dowrite(fd, buf, len)
275
276 #endif
277
278 static void
279 write_string (int          fd,
280               const gchar *string)
281 {
282   write (fd, string, strlen (string));
283 }
284
285 static GLogDomain*
286 g_log_find_domain_L (const gchar *log_domain)
287 {
288   register GLogDomain *domain;
289   
290   domain = g_log_domains;
291   while (domain)
292     {
293       if (strcmp (domain->log_domain, log_domain) == 0)
294         return domain;
295       domain = domain->next;
296     }
297   return NULL;
298 }
299
300 static GLogDomain*
301 g_log_domain_new_L (const gchar *log_domain)
302 {
303   register GLogDomain *domain;
304
305   domain = g_new (GLogDomain, 1);
306   domain->log_domain = g_strdup (log_domain);
307   domain->fatal_mask = G_LOG_FATAL_MASK;
308   domain->handlers = NULL;
309   
310   domain->next = g_log_domains;
311   g_log_domains = domain;
312   
313   return domain;
314 }
315
316 static void
317 g_log_domain_check_free_L (GLogDomain *domain)
318 {
319   if (domain->fatal_mask == G_LOG_FATAL_MASK &&
320       domain->handlers == NULL)
321     {
322       register GLogDomain *last, *work;
323       
324       last = NULL;  
325
326       work = g_log_domains;
327       while (work)
328         {
329           if (work == domain)
330             {
331               if (last)
332                 last->next = domain->next;
333               else
334                 g_log_domains = domain->next;
335               g_free (domain->log_domain);
336               g_free (domain);
337               break;
338             }
339           last = work;
340           work = last->next;
341         }  
342     }
343 }
344
345 static GLogFunc
346 g_log_domain_get_handler_L (GLogDomain  *domain,
347                             GLogLevelFlags log_level,
348                             gpointer    *data)
349 {
350   if (domain && log_level)
351     {
352       register GLogHandler *handler;
353       
354       handler = domain->handlers;
355       while (handler)
356         {
357           if ((handler->log_level & log_level) == log_level)
358             {
359               *data = handler->data;
360               return handler->log_func;
361             }
362           handler = handler->next;
363         }
364     }
365
366   *data = default_log_data;
367   return default_log_func;
368 }
369
370 /**
371  * g_log_set_always_fatal:
372  * @fatal_mask: the mask containing bits set for each level
373  *     of error which is to be fatal
374  *
375  * Sets the message levels which are always fatal, in any log domain.
376  * When a message with any of these levels is logged the program terminates.
377  * You can only set the levels defined by GLib to be fatal.
378  * %G_LOG_LEVEL_ERROR is always fatal.
379  *
380  * You can also make some message levels fatal at runtime by setting
381  * the %G_DEBUG environment variable (see
382  * <ulink url="glib-running.html">Running GLib Applications</ulink>).
383  *
384  * Returns: the old fatal mask
385  */
386 GLogLevelFlags
387 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
388 {
389   GLogLevelFlags old_mask;
390
391   /* restrict the global mask to levels that are known to glib
392    * since this setting applies to all domains
393    */
394   fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
395   /* force errors to be fatal */
396   fatal_mask |= G_LOG_LEVEL_ERROR;
397   /* remove bogus flag */
398   fatal_mask &= ~G_LOG_FLAG_FATAL;
399
400   g_mutex_lock (&g_messages_lock);
401   old_mask = g_log_always_fatal;
402   g_log_always_fatal = fatal_mask;
403   g_mutex_unlock (&g_messages_lock);
404
405   return old_mask;
406 }
407
408 /**
409  * g_log_set_fatal_mask:
410  * @log_domain: the log domain
411  * @fatal_mask: the new fatal mask
412  *
413  * Sets the log levels which are fatal in the given domain.
414  * %G_LOG_LEVEL_ERROR is always fatal.
415  *
416  * Returns: the old fatal mask for the log domain
417  */
418 GLogLevelFlags
419 g_log_set_fatal_mask (const gchar   *log_domain,
420                       GLogLevelFlags fatal_mask)
421 {
422   GLogLevelFlags old_flags;
423   register GLogDomain *domain;
424   
425   if (!log_domain)
426     log_domain = "";
427   
428   /* force errors to be fatal */
429   fatal_mask |= G_LOG_LEVEL_ERROR;
430   /* remove bogus flag */
431   fatal_mask &= ~G_LOG_FLAG_FATAL;
432   
433   g_mutex_lock (&g_messages_lock);
434
435   domain = g_log_find_domain_L (log_domain);
436   if (!domain)
437     domain = g_log_domain_new_L (log_domain);
438   old_flags = domain->fatal_mask;
439   
440   domain->fatal_mask = fatal_mask;
441   g_log_domain_check_free_L (domain);
442
443   g_mutex_unlock (&g_messages_lock);
444
445   return old_flags;
446 }
447
448 /**
449  * g_log_set_handler:
450  * @log_domain: the log domain, or %NULL for the default ""
451  *     application domain
452  * @log_levels: the log levels to apply the log handler for.
453  *     To handle fatal and recursive messages as well, combine
454  *     the log levels with the #G_LOG_FLAG_FATAL and
455  *     #G_LOG_FLAG_RECURSION bit flags.
456  * @log_func: the log handler function
457  * @user_data: data passed to the log handler
458  *
459  * Sets the log handler for a domain and a set of log levels.
460  * To handle fatal and recursive messages the @log_levels parameter
461  * must be combined with the #G_LOG_FLAG_FATAL and #G_LOG_FLAG_RECURSION
462  * bit flags.
463  *
464  * Note that since the #G_LOG_LEVEL_ERROR log level is always fatal, if
465  * you want to set a handler for this log level you must combine it with
466  * #G_LOG_FLAG_FATAL.
467  *
468  * <example>
469  * <title>Adding a log handler for all warning messages in the default
470  * (application) domain</title>
471  * <programlisting>
472  * g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
473  *                    | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
474  * </programlisting>
475  * </example>
476  *
477  * <example>
478  * <title>Adding a log handler for all critical messages from GTK+</title>
479  * <programlisting>
480  * g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
481  *                    | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
482  * </programlisting>
483  * </example>
484  *
485  * <example>
486  * <title>Adding a log handler for <emphasis>all</emphasis> messages from
487  * GLib</title>
488  * <programlisting>
489  * g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
490  *                    | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
491  * </programlisting>
492  * </example>
493  *
494  * Returns: the id of the new handler
495  */
496 guint
497 g_log_set_handler (const gchar   *log_domain,
498                    GLogLevelFlags log_levels,
499                    GLogFunc       log_func,
500                    gpointer       user_data)
501 {
502   static guint handler_id = 0;
503   GLogDomain *domain;
504   GLogHandler *handler;
505   
506   g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
507   g_return_val_if_fail (log_func != NULL, 0);
508   
509   if (!log_domain)
510     log_domain = "";
511
512   handler = g_new (GLogHandler, 1);
513
514   g_mutex_lock (&g_messages_lock);
515
516   domain = g_log_find_domain_L (log_domain);
517   if (!domain)
518     domain = g_log_domain_new_L (log_domain);
519   
520   handler->id = ++handler_id;
521   handler->log_level = log_levels;
522   handler->log_func = log_func;
523   handler->data = user_data;
524   handler->next = domain->handlers;
525   domain->handlers = handler;
526
527   g_mutex_unlock (&g_messages_lock);
528   
529   return handler_id;
530 }
531
532 /**
533  * g_log_set_default_handler:
534  * @log_func: the log handler function
535  * @user_data: data passed to the log handler
536  *
537  * Installs a default log handler which is used if no
538  * log handler has been set for the particular log domain
539  * and log level combination. By default, GLib uses
540  * g_log_default_handler() as default log handler.
541  *
542  * Returns: the previous default log handler
543  *
544  * Since: 2.6
545  */
546 GLogFunc
547 g_log_set_default_handler (GLogFunc log_func,
548                            gpointer user_data)
549 {
550   GLogFunc old_log_func;
551   
552   g_mutex_lock (&g_messages_lock);
553   old_log_func = default_log_func;
554   default_log_func = log_func;
555   default_log_data = user_data;
556   g_mutex_unlock (&g_messages_lock);
557   
558   return old_log_func;
559 }
560
561 /**
562  * g_test_log_set_fatal_handler:
563  * @log_func: the log handler function.
564  * @user_data: data passed to the log handler.
565  *
566  * Installs a non-error fatal log handler which can be
567  * used to decide whether log messages which are counted
568  * as fatal abort the program.
569  *
570  * The use case here is that you are running a test case
571  * that depends on particular libraries or circumstances
572  * and cannot prevent certain known critical or warning
573  * messages. So you install a handler that compares the
574  * domain and message to precisely not abort in such a case.
575  *
576  * Note that the handler is reset at the beginning of
577  * any test case, so you have to set it inside each test
578  * function which needs the special behavior.
579  *
580  * This handler has no effect on g_error messages.
581  *
582  * Since: 2.22
583  **/
584 void
585 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
586                               gpointer          user_data)
587 {
588   g_mutex_lock (&g_messages_lock);
589   fatal_log_func = log_func;
590   fatal_log_data = user_data;
591   g_mutex_unlock (&g_messages_lock);
592 }
593
594 /**
595  * g_log_remove_handler:
596  * @log_domain: the log domain
597  * @handler_id: the id of the handler, which was returned
598  *     in g_log_set_handler()
599  *
600  * Removes the log handler.
601  */
602 void
603 g_log_remove_handler (const gchar *log_domain,
604                       guint        handler_id)
605 {
606   register GLogDomain *domain;
607   
608   g_return_if_fail (handler_id > 0);
609   
610   if (!log_domain)
611     log_domain = "";
612   
613   g_mutex_lock (&g_messages_lock);
614   domain = g_log_find_domain_L (log_domain);
615   if (domain)
616     {
617       GLogHandler *work, *last;
618       
619       last = NULL;
620       work = domain->handlers;
621       while (work)
622         {
623           if (work->id == handler_id)
624             {
625               if (last)
626                 last->next = work->next;
627               else
628                 domain->handlers = work->next;
629               g_log_domain_check_free_L (domain); 
630               g_mutex_unlock (&g_messages_lock);
631               g_free (work);
632               return;
633             }
634           last = work;
635           work = last->next;
636         }
637     } 
638   g_mutex_unlock (&g_messages_lock);
639   g_warning ("%s: could not find handler with id `%d' for domain \"%s\"",
640              G_STRLOC, handler_id, log_domain);
641 }
642
643 /**
644  * g_logv:
645  * @log_domain: the log domain
646  * @log_level: the log level
647  * @format: the message format. See the printf() documentation
648  * @args: the parameters to insert into the format string
649  *
650  * Logs an error or debugging message.
651  *
652  * If the log level has been set as fatal, the abort()
653  * function is called to terminate the program.
654  */
655 void
656 g_logv (const gchar   *log_domain,
657         GLogLevelFlags log_level,
658         const gchar   *format,
659         va_list        args1)
660 {
661   gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
662   gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
663   gint i;
664
665   log_level &= G_LOG_LEVEL_MASK;
666   if (!log_level)
667     return;
668
669   for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
670     {
671       register GLogLevelFlags test_level;
672
673       test_level = 1 << i;
674       if (log_level & test_level)
675         {
676           GLogDomain *domain;
677           GLogFunc log_func;
678           GLogLevelFlags domain_fatal_mask;
679           gpointer data = NULL;
680           gboolean masquerade_fatal = FALSE;
681           guint depth;
682
683           if (was_fatal)
684             test_level |= G_LOG_FLAG_FATAL;
685           if (was_recursion)
686             test_level |= G_LOG_FLAG_RECURSION;
687
688           /* check recursion and lookup handler */
689           g_mutex_lock (&g_messages_lock);
690           depth = GPOINTER_TO_UINT (g_private_get (&g_log_depth));
691           domain = g_log_find_domain_L (log_domain ? log_domain : "");
692           if (depth)
693             test_level |= G_LOG_FLAG_RECURSION;
694           depth++;
695           domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
696           if ((domain_fatal_mask | g_log_always_fatal) & test_level)
697             test_level |= G_LOG_FLAG_FATAL;
698           if (test_level & G_LOG_FLAG_RECURSION)
699             log_func = _g_log_fallback_handler;
700           else
701             log_func = g_log_domain_get_handler_L (domain, test_level, &data);
702           domain = NULL;
703           g_mutex_unlock (&g_messages_lock);
704
705           g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
706
707
708           if (test_level & G_LOG_FLAG_RECURSION)
709             {
710               /* we use a stack buffer of fixed size, since we're likely
711                * in an out-of-memory situation
712                */
713               gchar buffer[1025];
714               gsize size G_GNUC_UNUSED;
715               va_list args2;
716
717               G_VA_COPY (args2, args1);
718               size = _g_vsnprintf (buffer, 1024, format, args2);
719               va_end (args2);
720
721               log_func (log_domain, test_level, buffer, data);
722             }
723           else
724             {
725               gchar *msg;
726               va_list args2;
727
728               G_VA_COPY (args2, args1);
729               msg = g_strdup_vprintf (format, args2);
730               va_end (args2);
731
732               log_func (log_domain, test_level, msg, data);
733
734               if ((test_level & G_LOG_FLAG_FATAL)
735                 && !(test_level & G_LOG_LEVEL_ERROR))
736                 {
737                   masquerade_fatal = fatal_log_func
738                     && !fatal_log_func (log_domain, test_level, msg, fatal_log_data);
739                 }
740
741               g_free (msg);
742             }
743
744           if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
745             {
746 #ifdef G_OS_WIN32
747               gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
748               
749               MessageBox (NULL, locale_msg, NULL,
750                           MB_ICONERROR|MB_SETFOREGROUND);
751               if (IsDebuggerPresent () && !(test_level & G_LOG_FLAG_RECURSION))
752                 G_BREAKPOINT ();
753               else
754                 abort ();
755 #else
756               if (!(test_level & G_LOG_FLAG_RECURSION))
757                 G_BREAKPOINT ();
758               else
759                 abort ();
760 #endif /* !G_OS_WIN32 */
761             }
762           
763           depth--;
764           g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
765         }
766     }
767 }
768
769 /**
770  * g_log:
771  * @log_domain: the log domain, usually #G_LOG_DOMAIN
772  * @log_level: the log level, either from #GLogLevelFlags
773  *     or a user-defined level
774  * @format: the message format. See the printf() documentation
775  * @...: the parameters to insert into the format string
776  *
777  * Logs an error or debugging message.
778  *
779  * If the log level has been set as fatal, the abort()
780  * function is called to terminate the program.
781  */
782 void
783 g_log (const gchar   *log_domain,
784        GLogLevelFlags log_level,
785        const gchar   *format,
786        ...)
787 {
788   va_list args;
789   
790   va_start (args, format);
791   g_logv (log_domain, log_level, format, args);
792   va_end (args);
793 }
794
795 void
796 g_return_if_fail_warning (const char *log_domain,
797                           const char *pretty_function,
798                           const char *expression)
799 {
800   g_log (log_domain,
801          G_LOG_LEVEL_CRITICAL,
802          "%s: assertion `%s' failed",
803          pretty_function,
804          expression);
805 }
806
807 void
808 g_warn_message (const char     *domain,
809                 const char     *file,
810                 int             line,
811                 const char     *func,
812                 const char     *warnexpr)
813 {
814   char *s, lstr[32];
815   g_snprintf (lstr, 32, "%d", line);
816   if (warnexpr)
817     s = g_strconcat ("(", file, ":", lstr, "):",
818                      func, func[0] ? ":" : "",
819                      " runtime check failed: (", warnexpr, ")", NULL);
820   else
821     s = g_strconcat ("(", file, ":", lstr, "):",
822                      func, func[0] ? ":" : "",
823                      " ", "code should not be reached", NULL);
824   g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
825   g_free (s);
826 }
827
828 void
829 g_assert_warning (const char *log_domain,
830                   const char *file,
831                   const int   line,
832                   const char *pretty_function,
833                   const char *expression)
834 {
835   g_log (log_domain,
836          G_LOG_LEVEL_ERROR,
837          expression 
838          ? "file %s: line %d (%s): assertion failed: (%s)"
839          : "file %s: line %d (%s): should not be reached",
840          file, 
841          line, 
842          pretty_function,
843          expression);
844   abort ();
845 }
846
847 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
848                             (wc == 0x7f) || \
849                             (wc >= 0x80 && wc < 0xa0)))
850      
851 static gchar*
852 strdup_convert (const gchar *string,
853                 const gchar *charset)
854 {
855   if (!g_utf8_validate (string, -1, NULL))
856     {
857       GString *gstring = g_string_new ("[Invalid UTF-8] ");
858       guchar *p;
859
860       for (p = (guchar *)string; *p; p++)
861         {
862           if (CHAR_IS_SAFE(*p) &&
863               !(*p == '\r' && *(p + 1) != '\n') &&
864               *p < 0x80)
865             g_string_append_c (gstring, *p);
866           else
867             g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
868         }
869       
870       return g_string_free (gstring, FALSE);
871     }
872   else
873     {
874       GError *err = NULL;
875       
876       gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
877       if (result)
878         return result;
879       else
880         {
881           /* Not thread-safe, but doesn't matter if we print the warning twice
882            */
883           static gboolean warned = FALSE; 
884           if (!warned)
885             {
886               warned = TRUE;
887               _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
888             }
889           g_error_free (err);
890           
891           return g_strdup (string);
892         }
893     }
894 }
895
896 /* For a radix of 8 we need at most 3 output bytes for 1 input
897  * byte. Additionally we might need up to 2 output bytes for the
898  * readix prefix and 1 byte for the trailing NULL.
899  */
900 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
901
902 static void
903 format_unsigned (gchar  *buf,
904                  gulong  num,
905                  guint   radix)
906 {
907   gulong tmp;
908   gchar c;
909   gint i, n;
910
911   /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
912
913   if (radix != 8 && radix != 10 && radix != 16)
914     {
915       *buf = '\000';
916       return;
917     }
918   
919   if (!num)
920     {
921       *buf++ = '0';
922       *buf = '\000';
923       return;
924     } 
925   
926   if (radix == 16)
927     {
928       *buf++ = '0';
929       *buf++ = 'x';
930     }
931   else if (radix == 8)
932     {
933       *buf++ = '0';
934     }
935         
936   n = 0;
937   tmp = num;
938   while (tmp)
939     {
940       tmp /= radix;
941       n++;
942     }
943
944   i = n;
945
946   /* Again we can't use g_assert; actually this check should _never_ fail. */
947   if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
948     {
949       *buf = '\000';
950       return;
951     }
952
953   while (num)
954     {
955       i--;
956       c = (num % radix);
957       if (c < 10)
958         buf[i] = c + '0';
959       else
960         buf[i] = c + 'a' - 10;
961       num /= radix;
962     }
963   
964   buf[n] = '\000';
965 }
966
967 /* string size big enough to hold level prefix */
968 #define STRING_BUFFER_SIZE      (FORMAT_UNSIGNED_BUFSIZE + 32)
969
970 #define ALERT_LEVELS            (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
971
972 static int
973 mklevel_prefix (gchar          level_prefix[STRING_BUFFER_SIZE],
974                 GLogLevelFlags log_level)
975 {
976   gboolean to_stdout = TRUE;
977
978   /* we may not call _any_ GLib functions here */
979
980   switch (log_level & G_LOG_LEVEL_MASK)
981     {
982     case G_LOG_LEVEL_ERROR:
983       strcpy (level_prefix, "ERROR");
984       to_stdout = FALSE;
985       break;
986     case G_LOG_LEVEL_CRITICAL:
987       strcpy (level_prefix, "CRITICAL");
988       to_stdout = FALSE;
989       break;
990     case G_LOG_LEVEL_WARNING:
991       strcpy (level_prefix, "WARNING");
992       to_stdout = FALSE;
993       break;
994     case G_LOG_LEVEL_MESSAGE:
995       strcpy (level_prefix, "Message");
996       to_stdout = FALSE;
997       break;
998     case G_LOG_LEVEL_INFO:
999       strcpy (level_prefix, "INFO");
1000       break;
1001     case G_LOG_LEVEL_DEBUG:
1002       strcpy (level_prefix, "DEBUG");
1003       break;
1004     default:
1005       if (log_level)
1006         {
1007           strcpy (level_prefix, "LOG-");
1008           format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
1009         }
1010       else
1011         strcpy (level_prefix, "LOG");
1012       break;
1013     }
1014   if (log_level & G_LOG_FLAG_RECURSION)
1015     strcat (level_prefix, " (recursed)");
1016   if (log_level & ALERT_LEVELS)
1017     strcat (level_prefix, " **");
1018
1019 #ifdef G_OS_WIN32
1020   win32_keep_fatal_message = (log_level & G_LOG_FLAG_FATAL) != 0;
1021 #endif
1022   return to_stdout ? 1 : 2;
1023 }
1024
1025 void
1026 _g_log_fallback_handler (const gchar   *log_domain,
1027                          GLogLevelFlags log_level,
1028                          const gchar   *message,
1029                          gpointer       unused_data)
1030 {
1031   gchar level_prefix[STRING_BUFFER_SIZE];
1032 #ifndef G_OS_WIN32
1033   gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
1034 #endif
1035   int fd;
1036
1037   /* we cannot call _any_ GLib functions in this fallback handler,
1038    * which is why we skip UTF-8 conversion, etc.
1039    * since we either recursed or ran out of memory, we're in a pretty
1040    * pathologic situation anyways, what we can do is giving the
1041    * the process ID unconditionally however.
1042    */
1043
1044   fd = mklevel_prefix (level_prefix, log_level);
1045   if (!message)
1046     message = "(NULL) message";
1047
1048 #ifndef G_OS_WIN32
1049   format_unsigned (pid_string, getpid (), 10);
1050 #endif
1051
1052   if (log_domain)
1053     write_string (fd, "\n");
1054   else
1055     write_string (fd, "\n** ");
1056
1057 #ifndef G_OS_WIN32
1058   write_string (fd, "(process:");
1059   write_string (fd, pid_string);
1060   write_string (fd, "): ");
1061 #endif
1062
1063   if (log_domain)
1064     {
1065       write_string (fd, log_domain);
1066       write_string (fd, "-");
1067     }
1068   write_string (fd, level_prefix);
1069   write_string (fd, ": ");
1070   write_string (fd, message);
1071 }
1072
1073 static void
1074 escape_string (GString *string)
1075 {
1076   const char *p = string->str;
1077   gunichar wc;
1078
1079   while (p < string->str + string->len)
1080     {
1081       gboolean safe;
1082             
1083       wc = g_utf8_get_char_validated (p, -1);
1084       if (wc == (gunichar)-1 || wc == (gunichar)-2)  
1085         {
1086           gchar *tmp;
1087           guint pos;
1088
1089           pos = p - string->str;
1090
1091           /* Emit invalid UTF-8 as hex escapes 
1092            */
1093           tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
1094           g_string_erase (string, pos, 1);
1095           g_string_insert (string, pos, tmp);
1096
1097           p = string->str + (pos + 4); /* Skip over escape sequence */
1098
1099           g_free (tmp);
1100           continue;
1101         }
1102       if (wc == '\r')
1103         {
1104           safe = *(p + 1) == '\n';
1105         }
1106       else
1107         {
1108           safe = CHAR_IS_SAFE (wc);
1109         }
1110       
1111       if (!safe)
1112         {
1113           gchar *tmp;
1114           guint pos;
1115
1116           pos = p - string->str;
1117           
1118           /* Largest char we escape is 0x0a, so we don't have to worry
1119            * about 8-digit \Uxxxxyyyy
1120            */
1121           tmp = g_strdup_printf ("\\u%04x", wc); 
1122           g_string_erase (string, pos, g_utf8_next_char (p) - p);
1123           g_string_insert (string, pos, tmp);
1124           g_free (tmp);
1125
1126           p = string->str + (pos + 6); /* Skip over escape sequence */
1127         }
1128       else
1129         p = g_utf8_next_char (p);
1130     }
1131 }
1132
1133 /**
1134  * g_log_default_handler:
1135  * @log_domain: the log domain of the message
1136  * @log_level: the level of the message
1137  * @message: the message
1138  * @unused_data: data passed from g_log() which is unused
1139  *
1140  * The default log handler set up by GLib; g_log_set_default_handler()
1141  * allows to install an alternate default log handler.
1142  * This is used if no log handler has been set for the particular log
1143  * domain and log level combination. It outputs the message to stderr
1144  * or stdout and if the log level is fatal it calls abort().
1145  *
1146  * stderr is used for levels %G_LOG_LEVEL_ERROR, %G_LOG_LEVEL_CRITICAL,
1147  * %G_LOG_LEVEL_WARNING and %G_LOG_LEVEL_MESSAGE. stdout is used for
1148  * the rest.
1149  */
1150 void
1151 g_log_default_handler (const gchar   *log_domain,
1152                        GLogLevelFlags log_level,
1153                        const gchar   *message,
1154                        gpointer       unused_data)
1155 {
1156   gchar level_prefix[STRING_BUFFER_SIZE], *string;
1157   GString *gstring;
1158   int fd;
1159
1160   /* we can be called externally with recursion for whatever reason */
1161   if (log_level & G_LOG_FLAG_RECURSION)
1162     {
1163       _g_log_fallback_handler (log_domain, log_level, message, unused_data);
1164       return;
1165     }
1166
1167   fd = mklevel_prefix (level_prefix, log_level);
1168
1169   gstring = g_string_new (NULL);
1170   if (log_level & ALERT_LEVELS)
1171     g_string_append (gstring, "\n");
1172   if (!log_domain)
1173     g_string_append (gstring, "** ");
1174
1175   if ((g_log_msg_prefix & log_level) == log_level)
1176     {
1177       const gchar *prg_name = g_get_prgname ();
1178       
1179       if (!prg_name)
1180         g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
1181       else
1182         g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
1183     }
1184
1185   if (log_domain)
1186     {
1187       g_string_append (gstring, log_domain);
1188       g_string_append_c (gstring, '-');
1189     }
1190   g_string_append (gstring, level_prefix);
1191
1192   g_string_append (gstring, ": ");
1193   if (!message)
1194     g_string_append (gstring, "(NULL) message");
1195   else
1196     {
1197       GString *msg;
1198       const gchar *charset;
1199
1200       msg = g_string_new (message);
1201       escape_string (msg);
1202
1203       if (g_get_charset (&charset))
1204         g_string_append (gstring, msg->str);    /* charset is UTF-8 already */
1205       else
1206         {
1207           string = strdup_convert (msg->str, charset);
1208           g_string_append (gstring, string);
1209           g_free (string);
1210         }
1211
1212       g_string_free (msg, TRUE);
1213     }
1214   g_string_append (gstring, "\n");
1215
1216   string = g_string_free (gstring, FALSE);
1217
1218   write_string (fd, string);
1219   g_free (string);
1220 }
1221
1222 /**
1223  * g_set_print_handler:
1224  * @func: the new print handler
1225  *
1226  * Sets the print handler.
1227  *
1228  * Any messages passed to g_print() will be output via
1229  * the new handler. The default handler simply outputs
1230  * the message to stdout. By providing your own handler
1231  * you can redirect the output, to a GTK+ widget or a
1232  * log file for example.
1233  *
1234  * Returns: the old print handler
1235  */
1236 GPrintFunc
1237 g_set_print_handler (GPrintFunc func)
1238 {
1239   GPrintFunc old_print_func;
1240
1241   g_mutex_lock (&g_messages_lock);
1242   old_print_func = glib_print_func;
1243   glib_print_func = func;
1244   g_mutex_unlock (&g_messages_lock);
1245
1246   return old_print_func;
1247 }
1248
1249 /**
1250  * g_print:
1251  * @format: the message format. See the printf() documentation
1252  * @...: the parameters to insert into the format string
1253  *
1254  * Outputs a formatted message via the print handler.
1255  * The default print handler simply outputs the message to stdout.
1256  *
1257  * g_print() should not be used from within libraries for debugging
1258  * messages, since it may be redirected by applications to special
1259  * purpose message windows or even files. Instead, libraries should
1260  * use g_log(), or the convenience functions g_message(), g_warning()
1261  * and g_error().
1262  */
1263 void
1264 g_print (const gchar *format,
1265          ...)
1266 {
1267   va_list args;
1268   gchar *string;
1269   GPrintFunc local_glib_print_func;
1270
1271   g_return_if_fail (format != NULL);
1272
1273   va_start (args, format);
1274   string = g_strdup_vprintf (format, args);
1275   va_end (args);
1276
1277   g_mutex_lock (&g_messages_lock);
1278   local_glib_print_func = glib_print_func;
1279   g_mutex_unlock (&g_messages_lock);
1280
1281   if (local_glib_print_func)
1282     local_glib_print_func (string);
1283   else
1284     {
1285       const gchar *charset;
1286
1287       if (g_get_charset (&charset))
1288         fputs (string, stdout); /* charset is UTF-8 already */
1289       else
1290         {
1291           gchar *lstring = strdup_convert (string, charset);
1292
1293           fputs (lstring, stdout);
1294           g_free (lstring);
1295         }
1296       fflush (stdout);
1297     }
1298   g_free (string);
1299 }
1300
1301 /**
1302  * g_set_printerr_handler:
1303  * @func: the new error message handler
1304  *
1305  * Sets the handler for printing error messages.
1306  *
1307  * Any messages passed to g_printerr() will be output via
1308  * the new handler. The default handler simply outputs the
1309  * message to stderr. By providing your own handler you can
1310  * redirect the output, to a GTK+ widget or a log file for
1311  * example.
1312  *
1313  * Returns: the old error message handler
1314  */
1315 GPrintFunc
1316 g_set_printerr_handler (GPrintFunc func)
1317 {
1318   GPrintFunc old_printerr_func;
1319
1320   g_mutex_lock (&g_messages_lock);
1321   old_printerr_func = glib_printerr_func;
1322   glib_printerr_func = func;
1323   g_mutex_unlock (&g_messages_lock);
1324
1325   return old_printerr_func;
1326 }
1327
1328 /**
1329  * g_printerr:
1330  * @format: the message format. See the printf() documentation
1331  * @...: the parameters to insert into the format string
1332  *
1333  * Outputs a formatted message via the error message handler.
1334  * The default handler simply outputs the message to stderr.
1335  *
1336  * g_printerr() should not be used from within libraries.
1337  * Instead g_log() should be used, or the convenience functions
1338  * g_message(), g_warning() and g_error().
1339  */
1340 void
1341 g_printerr (const gchar *format,
1342             ...)
1343 {
1344   va_list args;
1345   gchar *string;
1346   GPrintFunc local_glib_printerr_func;
1347
1348   g_return_if_fail (format != NULL);
1349
1350   va_start (args, format);
1351   string = g_strdup_vprintf (format, args);
1352   va_end (args);
1353
1354   g_mutex_lock (&g_messages_lock);
1355   local_glib_printerr_func = glib_printerr_func;
1356   g_mutex_unlock (&g_messages_lock);
1357
1358   if (local_glib_printerr_func)
1359     local_glib_printerr_func (string);
1360   else
1361     {
1362       const gchar *charset;
1363
1364       if (g_get_charset (&charset))
1365         fputs (string, stderr); /* charset is UTF-8 already */
1366       else
1367         {
1368           gchar *lstring = strdup_convert (string, charset);
1369
1370           fputs (lstring, stderr);
1371           g_free (lstring);
1372         }
1373       fflush (stderr);
1374     }
1375   g_free (string);
1376 }
1377
1378 /**
1379  * g_printf_string_upper_bound:
1380  * @format: the format string. See the printf() documentation
1381  * @args: the parameters to be inserted into the format string
1382  *
1383  * Calculates the maximum space needed to store the output
1384  * of the sprintf() function.
1385  *
1386  * Returns: the maximum space needed to store the formatted string
1387  */
1388 gsize
1389 g_printf_string_upper_bound (const gchar *format,
1390                              va_list      args)
1391 {
1392   gchar c;
1393   return _g_vsnprintf (&c, 1, format, args) + 1;
1394 }