documentation fixes
[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: 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        args1)
661 {
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;
665
666   log_level &= G_LOG_LEVEL_MASK;
667   if (!log_level)
668     return;
669
670   for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
671     {
672       register GLogLevelFlags test_level;
673
674       test_level = 1 << i;
675       if (log_level & test_level)
676         {
677           GLogDomain *domain;
678           GLogFunc log_func;
679           GLogLevelFlags domain_fatal_mask;
680           gpointer data = NULL;
681           gboolean masquerade_fatal = FALSE;
682           guint depth;
683
684           if (was_fatal)
685             test_level |= G_LOG_FLAG_FATAL;
686           if (was_recursion)
687             test_level |= G_LOG_FLAG_RECURSION;
688
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);
705
706           g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
707
708
709           if (test_level & G_LOG_FLAG_RECURSION)
710             {
711               /* we use a stack buffer of fixed size, since we're likely
712                * in an out-of-memory situation
713                */
714               gchar buffer[1025];
715               gsize size G_GNUC_UNUSED;
716               va_list args2;
717
718               G_VA_COPY (args2, args1);
719               size = _g_vsnprintf (buffer, 1024, format, args2);
720               va_end (args2);
721
722               log_func (log_domain, test_level, buffer, data);
723             }
724           else
725             {
726               gchar *msg;
727               va_list args2;
728
729               G_VA_COPY (args2, args1);
730               msg = g_strdup_vprintf (format, args2);
731               va_end (args2);
732
733               log_func (log_domain, test_level, msg, data);
734
735               if ((test_level & G_LOG_FLAG_FATAL)
736                 && !(test_level & G_LOG_LEVEL_ERROR))
737                 {
738                   masquerade_fatal = fatal_log_func
739                     && !fatal_log_func (log_domain, test_level, msg, fatal_log_data);
740                 }
741
742               g_free (msg);
743             }
744
745           if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
746             {
747 #ifdef G_OS_WIN32
748               gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
749               
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 */
762             }
763           
764           depth--;
765           g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
766         }
767     }
768 }
769
770 /**
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
777  *
778  * Logs an error or debugging message.
779  *
780  * If the log level has been set as fatal, the abort()
781  * function is called to terminate the program.
782  */
783 void
784 g_log (const gchar   *log_domain,
785        GLogLevelFlags log_level,
786        const gchar   *format,
787        ...)
788 {
789   va_list args;
790   
791   va_start (args, format);
792   g_logv (log_domain, log_level, format, args);
793   va_end (args);
794 }
795
796 void
797 g_return_if_fail_warning (const char *log_domain,
798                           const char *pretty_function,
799                           const char *expression)
800 {
801   g_log (log_domain,
802          G_LOG_LEVEL_CRITICAL,
803          "%s: assertion `%s' failed",
804          pretty_function,
805          expression);
806 }
807
808 void
809 g_warn_message (const char     *domain,
810                 const char     *file,
811                 int             line,
812                 const char     *func,
813                 const char     *warnexpr)
814 {
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);
827 }
828
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)
835 {
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 ();
846 }
847
848 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
849                             (wc == 0x7f) || \
850                             (wc >= 0x80 && wc < 0xa0)))
851      
852 static gchar*
853 strdup_convert (const gchar *string,
854                 const gchar *charset)
855 {
856   if (!g_utf8_validate (string, -1, NULL))
857     {
858       GString *gstring = g_string_new ("[Invalid UTF-8] ");
859       guchar *p;
860
861       for (p = (guchar *)string; *p; p++)
862         {
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);
869         }
870       
871       return g_string_free (gstring, FALSE);
872     }
873   else
874     {
875       GError *err = NULL;
876       
877       gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
878       if (result)
879         return result;
880       else
881         {
882           /* Not thread-safe, but doesn't matter if we print the warning twice
883            */
884           static gboolean warned = FALSE; 
885           if (!warned)
886             {
887               warned = TRUE;
888               _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
889             }
890           g_error_free (err);
891           
892           return g_strdup (string);
893         }
894     }
895 }
896
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.
900  */
901 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
902
903 static void
904 format_unsigned (gchar  *buf,
905                  gulong  num,
906                  guint   radix)
907 {
908   gulong tmp;
909   gchar c;
910   gint i, n;
911
912   /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
913
914   if (radix != 8 && radix != 10 && radix != 16)
915     {
916       *buf = '\000';
917       return;
918     }
919   
920   if (!num)
921     {
922       *buf++ = '0';
923       *buf = '\000';
924       return;
925     } 
926   
927   if (radix == 16)
928     {
929       *buf++ = '0';
930       *buf++ = 'x';
931     }
932   else if (radix == 8)
933     {
934       *buf++ = '0';
935     }
936         
937   n = 0;
938   tmp = num;
939   while (tmp)
940     {
941       tmp /= radix;
942       n++;
943     }
944
945   i = n;
946
947   /* Again we can't use g_assert; actually this check should _never_ fail. */
948   if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
949     {
950       *buf = '\000';
951       return;
952     }
953
954   while (num)
955     {
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;
963     }
964   
965   buf[n] = '\000';
966 }
967
968 /* string size big enough to hold level prefix */
969 #define STRING_BUFFER_SIZE      (FORMAT_UNSIGNED_BUFSIZE + 32)
970
971 #define ALERT_LEVELS            (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
972
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)
977
978 static int
979 mklevel_prefix (gchar          level_prefix[STRING_BUFFER_SIZE],
980                 GLogLevelFlags log_level)
981 {
982   gboolean to_stdout = TRUE;
983
984   /* we may not call _any_ GLib functions here */
985
986   switch (log_level & G_LOG_LEVEL_MASK)
987     {
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)
1012         {
1013           strcpy (level_prefix, "LOG-");
1014           format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
1015         }
1016       else
1017         strcpy (level_prefix, "LOG");
1018       break;
1019     }
1020   if (log_level & G_LOG_FLAG_RECURSION)
1021     strcat (level_prefix, " (recursed)");
1022   if (log_level & ALERT_LEVELS)
1023     strcat (level_prefix, " **");
1024
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;
1029 }
1030
1031 void
1032 _g_log_fallback_handler (const gchar   *log_domain,
1033                          GLogLevelFlags log_level,
1034                          const gchar   *message,
1035                          gpointer       unused_data)
1036 {
1037   gchar level_prefix[STRING_BUFFER_SIZE];
1038 #ifndef G_OS_WIN32
1039   gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
1040 #endif
1041   int fd;
1042
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.
1048    */
1049
1050   fd = mklevel_prefix (level_prefix, log_level);
1051   if (!message)
1052     message = "(NULL) message";
1053
1054 #ifndef G_OS_WIN32
1055   format_unsigned (pid_string, getpid (), 10);
1056 #endif
1057
1058   if (log_domain)
1059     write_string (fd, "\n");
1060   else
1061     write_string (fd, "\n** ");
1062
1063 #ifndef G_OS_WIN32
1064   write_string (fd, "(process:");
1065   write_string (fd, pid_string);
1066   write_string (fd, "): ");
1067 #endif
1068
1069   if (log_domain)
1070     {
1071       write_string (fd, log_domain);
1072       write_string (fd, "-");
1073     }
1074   write_string (fd, level_prefix);
1075   write_string (fd, ": ");
1076   write_string (fd, message);
1077 }
1078
1079 static void
1080 escape_string (GString *string)
1081 {
1082   const char *p = string->str;
1083   gunichar wc;
1084
1085   while (p < string->str + string->len)
1086     {
1087       gboolean safe;
1088             
1089       wc = g_utf8_get_char_validated (p, -1);
1090       if (wc == (gunichar)-1 || wc == (gunichar)-2)  
1091         {
1092           gchar *tmp;
1093           guint pos;
1094
1095           pos = p - string->str;
1096
1097           /* Emit invalid UTF-8 as hex escapes 
1098            */
1099           tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
1100           g_string_erase (string, pos, 1);
1101           g_string_insert (string, pos, tmp);
1102
1103           p = string->str + (pos + 4); /* Skip over escape sequence */
1104
1105           g_free (tmp);
1106           continue;
1107         }
1108       if (wc == '\r')
1109         {
1110           safe = *(p + 1) == '\n';
1111         }
1112       else
1113         {
1114           safe = CHAR_IS_SAFE (wc);
1115         }
1116       
1117       if (!safe)
1118         {
1119           gchar *tmp;
1120           guint pos;
1121
1122           pos = p - string->str;
1123           
1124           /* Largest char we escape is 0x0a, so we don't have to worry
1125            * about 8-digit \Uxxxxyyyy
1126            */
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);
1131
1132           p = string->str + (pos + 6); /* Skip over escape sequence */
1133         }
1134       else
1135         p = g_utf8_next_char (p);
1136     }
1137 }
1138
1139 /**
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
1145  *
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().
1151  *
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>
1171  *
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.
1175  */
1176 void
1177 g_log_default_handler (const gchar   *log_domain,
1178                        GLogLevelFlags log_level,
1179                        const gchar   *message,
1180                        gpointer       unused_data)
1181 {
1182   gchar level_prefix[STRING_BUFFER_SIZE], *string;
1183   GString *gstring;
1184   int fd;
1185   const gchar *domains;
1186
1187   if ((log_level & DEFAULT_LEVELS) || (log_level >> G_LOG_LEVEL_USER_SHIFT))
1188     goto emit;
1189
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;
1195
1196  emit:
1197   /* we can be called externally with recursion for whatever reason */
1198   if (log_level & G_LOG_FLAG_RECURSION)
1199     {
1200       _g_log_fallback_handler (log_domain, log_level, message, unused_data);
1201       return;
1202     }
1203
1204   fd = mklevel_prefix (level_prefix, log_level);
1205
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, "** ");
1211
1212   if ((g_log_msg_prefix & log_level) == log_level)
1213     {
1214       const gchar *prg_name = g_get_prgname ();
1215       
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 ());
1220     }
1221
1222   if (log_domain)
1223     {
1224       g_string_append (gstring, log_domain);
1225       g_string_append_c (gstring, '-');
1226     }
1227   g_string_append (gstring, level_prefix);
1228
1229   g_string_append (gstring, ": ");
1230   if (!message)
1231     g_string_append (gstring, "(NULL) message");
1232   else
1233     {
1234       GString *msg;
1235       const gchar *charset;
1236
1237       msg = g_string_new (message);
1238       escape_string (msg);
1239
1240       if (g_get_charset (&charset))
1241         g_string_append (gstring, msg->str);    /* charset is UTF-8 already */
1242       else
1243         {
1244           string = strdup_convert (msg->str, charset);
1245           g_string_append (gstring, string);
1246           g_free (string);
1247         }
1248
1249       g_string_free (msg, TRUE);
1250     }
1251   g_string_append (gstring, "\n");
1252
1253   string = g_string_free (gstring, FALSE);
1254
1255   write_string (fd, string);
1256   g_free (string);
1257 }
1258
1259 /**
1260  * g_set_print_handler:
1261  * @func: the new print handler
1262  *
1263  * Sets the print handler.
1264  *
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.
1270  *
1271  * Returns: the old print handler
1272  */
1273 GPrintFunc
1274 g_set_print_handler (GPrintFunc func)
1275 {
1276   GPrintFunc old_print_func;
1277
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);
1282
1283   return old_print_func;
1284 }
1285
1286 /**
1287  * g_print:
1288  * @format: the message format. See the printf() documentation
1289  * @...: the parameters to insert into the format string
1290  *
1291  * Outputs a formatted message via the print handler.
1292  * The default print handler simply outputs the message to stdout.
1293  *
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().
1299  */
1300 void
1301 g_print (const gchar *format,
1302          ...)
1303 {
1304   va_list args;
1305   gchar *string;
1306   GPrintFunc local_glib_print_func;
1307
1308   g_return_if_fail (format != NULL);
1309
1310   va_start (args, format);
1311   string = g_strdup_vprintf (format, args);
1312   va_end (args);
1313
1314   g_mutex_lock (&g_messages_lock);
1315   local_glib_print_func = glib_print_func;
1316   g_mutex_unlock (&g_messages_lock);
1317
1318   if (local_glib_print_func)
1319     local_glib_print_func (string);
1320   else
1321     {
1322       const gchar *charset;
1323
1324       if (g_get_charset (&charset))
1325         fputs (string, stdout); /* charset is UTF-8 already */
1326       else
1327         {
1328           gchar *lstring = strdup_convert (string, charset);
1329
1330           fputs (lstring, stdout);
1331           g_free (lstring);
1332         }
1333       fflush (stdout);
1334     }
1335   g_free (string);
1336 }
1337
1338 /**
1339  * g_set_printerr_handler:
1340  * @func: the new error message handler
1341  *
1342  * Sets the handler for printing error messages.
1343  *
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.
1349  *
1350  * Returns: the old error message handler
1351  */
1352 GPrintFunc
1353 g_set_printerr_handler (GPrintFunc func)
1354 {
1355   GPrintFunc old_printerr_func;
1356
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);
1361
1362   return old_printerr_func;
1363 }
1364
1365 /**
1366  * g_printerr:
1367  * @format: the message format. See the printf() documentation
1368  * @...: the parameters to insert into the format string
1369  *
1370  * Outputs a formatted message via the error message handler.
1371  * The default handler simply outputs the message to stderr.
1372  *
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().
1376  */
1377 void
1378 g_printerr (const gchar *format,
1379             ...)
1380 {
1381   va_list args;
1382   gchar *string;
1383   GPrintFunc local_glib_printerr_func;
1384
1385   g_return_if_fail (format != NULL);
1386
1387   va_start (args, format);
1388   string = g_strdup_vprintf (format, args);
1389   va_end (args);
1390
1391   g_mutex_lock (&g_messages_lock);
1392   local_glib_printerr_func = glib_printerr_func;
1393   g_mutex_unlock (&g_messages_lock);
1394
1395   if (local_glib_printerr_func)
1396     local_glib_printerr_func (string);
1397   else
1398     {
1399       const gchar *charset;
1400
1401       if (g_get_charset (&charset))
1402         fputs (string, stderr); /* charset is UTF-8 already */
1403       else
1404         {
1405           gchar *lstring = strdup_convert (string, charset);
1406
1407           fputs (lstring, stderr);
1408           g_free (lstring);
1409         }
1410       fflush (stderr);
1411     }
1412   g_free (string);
1413 }
1414
1415 /**
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
1419  *
1420  * Calculates the maximum space needed to store the output
1421  * of the sprintf() function.
1422  *
1423  * Returns: the maximum space needed to store the formatted string
1424  */
1425 gsize
1426 g_printf_string_upper_bound (const gchar *format,
1427                              va_list      args)
1428 {
1429   gchar c;
1430   return _g_vsnprintf (&c, 1, format, args) + 1;
1431 }