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