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