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