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