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