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