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