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