Deprecate g_thread_init()
[platform/upstream/glib.git] / glib / gmessages.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/.
25  */
26
27 /*
28  * MT safe
29  */
30
31 /**
32  * SECTION:warnings
33  * @Title: Message Output and Debugging Functions
34  * @Short_description: functions to output messages and help debug applications
35  *
36  * These functions provide support for outputting messages.
37  *
38  * The <function>g_return</function> family of macros (g_return_if_fail(),
39  * g_return_val_if_fail(), g_return_if_reached(), g_return_val_if_reached())
40  * should only be used for programming errors, a typical use case is
41  * checking for invalid parameters at the beginning of a public function.
42  * They should not be used if you just mean "if (error) return", they
43  * should only be used if you mean "if (bug in program) return".
44  * The program behavior is generally considered undefined after one
45  * of these checks fails. They are not intended for normal control
46  * flow, only to give a perhaps-helpful warning before giving up.
47  */
48
49 #include "config.h"
50
51 #include <stdlib.h>
52 #include <stdarg.h>
53 #include <stdio.h>
54 #include <string.h>
55 #ifdef HAVE_UNISTD_H
56 #include <unistd.h>
57 #endif
58 #include <signal.h>
59 #include <locale.h>
60 #include <errno.h>
61
62 #include "gmessages.h"
63 #include "glib-init.h"
64
65 #include "gbacktrace.h"
66 #include "gconvert.h"
67 #include "gmem.h"
68 #include "gprintfint.h"
69 #include "gtestutils.h"
70 #include "gthread.h"
71 #include "gstrfuncs.h"
72 #include "gstring.h"
73
74 #ifdef G_OS_WIN32
75 #include <process.h>            /* For getpid() */
76 #include <io.h>
77 #  define STRICT                /* Strict typing, please */
78 #  define _WIN32_WINDOWS 0x0401 /* to get IsDebuggerPresent */
79 #  include <windows.h>
80 #  undef STRICT
81 #endif
82
83
84 /* --- structures --- */
85 typedef struct _GLogDomain      GLogDomain;
86 typedef struct _GLogHandler     GLogHandler;
87 struct _GLogDomain
88 {
89   gchar         *log_domain;
90   GLogLevelFlags fatal_mask;
91   GLogHandler   *handlers;
92   GLogDomain    *next;
93 };
94 struct _GLogHandler
95 {
96   guint          id;
97   GLogLevelFlags log_level;
98   GLogFunc       log_func;
99   gpointer       data;
100   GLogHandler   *next;
101 };
102
103
104 /* --- variables --- */
105 static GMutex         g_messages_lock;
106 static GLogDomain    *g_log_domains = NULL;
107 static GPrintFunc     glib_print_func = NULL;
108 static GPrintFunc     glib_printerr_func = NULL;
109 static GPrivate       g_log_depth;
110 static GLogFunc       default_log_func = g_log_default_handler;
111 static gpointer       default_log_data = NULL;
112 static GTestLogFatalFunc fatal_log_func = NULL;
113 static gpointer          fatal_log_data;
114
115 /* --- functions --- */
116 #ifdef G_OS_WIN32
117 #  define STRICT
118 #  include <windows.h>
119 #  undef STRICT
120 static gboolean win32_keep_fatal_message = FALSE;
121
122 /* This default message will usually be overwritten. */
123 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
124  * called with huge strings, is it?
125  */
126 static gchar  fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
127 static gchar *fatal_msg_ptr = fatal_msg_buf;
128
129 #undef write
130 static inline int
131 dowrite (int          fd,
132          const void  *buf,
133          unsigned int len)
134 {
135   if (win32_keep_fatal_message)
136     {
137       memcpy (fatal_msg_ptr, buf, len);
138       fatal_msg_ptr += len;
139       *fatal_msg_ptr = 0;
140       return len;
141     }
142
143   write (fd, buf, len);
144
145   return len;
146 }
147 #define write(fd, buf, len) dowrite(fd, buf, len)
148
149 #endif
150
151 static void
152 write_string (int          fd,
153               const gchar *string)
154 {
155   write (fd, string, strlen (string));
156 }
157
158 static GLogDomain*
159 g_log_find_domain_L (const gchar *log_domain)
160 {
161   register GLogDomain *domain;
162   
163   domain = g_log_domains;
164   while (domain)
165     {
166       if (strcmp (domain->log_domain, log_domain) == 0)
167         return domain;
168       domain = domain->next;
169     }
170   return NULL;
171 }
172
173 static GLogDomain*
174 g_log_domain_new_L (const gchar *log_domain)
175 {
176   register GLogDomain *domain;
177
178   domain = g_new (GLogDomain, 1);
179   domain->log_domain = g_strdup (log_domain);
180   domain->fatal_mask = G_LOG_FATAL_MASK;
181   domain->handlers = NULL;
182   
183   domain->next = g_log_domains;
184   g_log_domains = domain;
185   
186   return domain;
187 }
188
189 static void
190 g_log_domain_check_free_L (GLogDomain *domain)
191 {
192   if (domain->fatal_mask == G_LOG_FATAL_MASK &&
193       domain->handlers == NULL)
194     {
195       register GLogDomain *last, *work;
196       
197       last = NULL;  
198
199       work = g_log_domains;
200       while (work)
201         {
202           if (work == domain)
203             {
204               if (last)
205                 last->next = domain->next;
206               else
207                 g_log_domains = domain->next;
208               g_free (domain->log_domain);
209               g_free (domain);
210               break;
211             }
212           last = work;
213           work = last->next;
214         }  
215     }
216 }
217
218 static GLogFunc
219 g_log_domain_get_handler_L (GLogDomain  *domain,
220                             GLogLevelFlags log_level,
221                             gpointer    *data)
222 {
223   if (domain && log_level)
224     {
225       register GLogHandler *handler;
226       
227       handler = domain->handlers;
228       while (handler)
229         {
230           if ((handler->log_level & log_level) == log_level)
231             {
232               *data = handler->data;
233               return handler->log_func;
234             }
235           handler = handler->next;
236         }
237     }
238
239   *data = default_log_data;
240   return default_log_func;
241 }
242
243 GLogLevelFlags
244 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
245 {
246   GLogLevelFlags old_mask;
247
248   /* restrict the global mask to levels that are known to glib
249    * since this setting applies to all domains
250    */
251   fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
252   /* force errors to be fatal */
253   fatal_mask |= G_LOG_LEVEL_ERROR;
254   /* remove bogus flag */
255   fatal_mask &= ~G_LOG_FLAG_FATAL;
256
257   g_mutex_lock (&g_messages_lock);
258   old_mask = g_log_always_fatal;
259   g_log_always_fatal = fatal_mask;
260   g_mutex_unlock (&g_messages_lock);
261
262   return old_mask;
263 }
264
265 GLogLevelFlags
266 g_log_set_fatal_mask (const gchar   *log_domain,
267                       GLogLevelFlags fatal_mask)
268 {
269   GLogLevelFlags old_flags;
270   register GLogDomain *domain;
271   
272   if (!log_domain)
273     log_domain = "";
274   
275   /* force errors to be fatal */
276   fatal_mask |= G_LOG_LEVEL_ERROR;
277   /* remove bogus flag */
278   fatal_mask &= ~G_LOG_FLAG_FATAL;
279   
280   g_mutex_lock (&g_messages_lock);
281
282   domain = g_log_find_domain_L (log_domain);
283   if (!domain)
284     domain = g_log_domain_new_L (log_domain);
285   old_flags = domain->fatal_mask;
286   
287   domain->fatal_mask = fatal_mask;
288   g_log_domain_check_free_L (domain);
289
290   g_mutex_unlock (&g_messages_lock);
291
292   return old_flags;
293 }
294
295 guint
296 g_log_set_handler (const gchar   *log_domain,
297                    GLogLevelFlags log_levels,
298                    GLogFunc       log_func,
299                    gpointer       user_data)
300 {
301   static guint handler_id = 0;
302   GLogDomain *domain;
303   GLogHandler *handler;
304   
305   g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
306   g_return_val_if_fail (log_func != NULL, 0);
307   
308   if (!log_domain)
309     log_domain = "";
310
311   handler = g_new (GLogHandler, 1);
312
313   g_mutex_lock (&g_messages_lock);
314
315   domain = g_log_find_domain_L (log_domain);
316   if (!domain)
317     domain = g_log_domain_new_L (log_domain);
318   
319   handler->id = ++handler_id;
320   handler->log_level = log_levels;
321   handler->log_func = log_func;
322   handler->data = user_data;
323   handler->next = domain->handlers;
324   domain->handlers = handler;
325
326   g_mutex_unlock (&g_messages_lock);
327   
328   return handler_id;
329 }
330
331 GLogFunc
332 g_log_set_default_handler (GLogFunc log_func,
333                            gpointer user_data)
334 {
335   GLogFunc old_log_func;
336   
337   g_mutex_lock (&g_messages_lock);
338   old_log_func = default_log_func;
339   default_log_func = log_func;
340   default_log_data = user_data;
341   g_mutex_unlock (&g_messages_lock);
342   
343   return old_log_func;
344 }
345
346 /**
347  * g_test_log_set_fatal_handler:
348  * @log_func: the log handler function.
349  * @user_data: data passed to the log handler.
350  *
351  * Installs a non-error fatal log handler which can be
352  * used to decide whether log messages which are counted
353  * as fatal abort the program.
354  *
355  * The use case here is that you are running a test case
356  * that depends on particular libraries or circumstances
357  * and cannot prevent certain known critical or warning
358  * messages. So you install a handler that compares the
359  * domain and message to precisely not abort in such a case.
360  *
361  * Note that the handler is reset at the beginning of
362  * any test case, so you have to set it inside each test
363  * function which needs the special behavior.
364  *
365  * This handler has no effect on g_error messages.
366  *
367  * Since: 2.22
368  **/
369 void
370 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
371                               gpointer          user_data)
372 {
373   g_mutex_lock (&g_messages_lock);
374   fatal_log_func = log_func;
375   fatal_log_data = user_data;
376   g_mutex_unlock (&g_messages_lock);
377 }
378
379 void
380 g_log_remove_handler (const gchar *log_domain,
381                       guint        handler_id)
382 {
383   register GLogDomain *domain;
384   
385   g_return_if_fail (handler_id > 0);
386   
387   if (!log_domain)
388     log_domain = "";
389   
390   g_mutex_lock (&g_messages_lock);
391   domain = g_log_find_domain_L (log_domain);
392   if (domain)
393     {
394       GLogHandler *work, *last;
395       
396       last = NULL;
397       work = domain->handlers;
398       while (work)
399         {
400           if (work->id == handler_id)
401             {
402               if (last)
403                 last->next = work->next;
404               else
405                 domain->handlers = work->next;
406               g_log_domain_check_free_L (domain); 
407               g_mutex_unlock (&g_messages_lock);
408               g_free (work);
409               return;
410             }
411           last = work;
412           work = last->next;
413         }
414     } 
415   g_mutex_unlock (&g_messages_lock);
416   g_warning ("%s: could not find handler with id `%d' for domain \"%s\"",
417              G_STRLOC, handler_id, log_domain);
418 }
419
420 void
421 g_logv (const gchar   *log_domain,
422         GLogLevelFlags log_level,
423         const gchar   *format,
424         va_list        args1)
425 {
426   gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
427   gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
428   gint i;
429
430   log_level &= G_LOG_LEVEL_MASK;
431   if (!log_level)
432     return;
433
434   for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
435     {
436       register GLogLevelFlags test_level;
437
438       test_level = 1 << i;
439       if (log_level & test_level)
440         {
441           GLogDomain *domain;
442           GLogFunc log_func;
443           GLogLevelFlags domain_fatal_mask;
444           gpointer data = NULL;
445           gboolean masquerade_fatal = FALSE;
446           guint depth;
447
448           if (was_fatal)
449             test_level |= G_LOG_FLAG_FATAL;
450           if (was_recursion)
451             test_level |= G_LOG_FLAG_RECURSION;
452
453           /* check recursion and lookup handler */
454           g_mutex_lock (&g_messages_lock);
455           depth = GPOINTER_TO_UINT (g_private_get (&g_log_depth));
456           domain = g_log_find_domain_L (log_domain ? log_domain : "");
457           if (depth)
458             test_level |= G_LOG_FLAG_RECURSION;
459           depth++;
460           domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
461           if ((domain_fatal_mask | g_log_always_fatal) & test_level)
462             test_level |= G_LOG_FLAG_FATAL;
463           if (test_level & G_LOG_FLAG_RECURSION)
464             log_func = _g_log_fallback_handler;
465           else
466             log_func = g_log_domain_get_handler_L (domain, test_level, &data);
467           domain = NULL;
468           g_mutex_unlock (&g_messages_lock);
469
470           g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
471
472
473           if (test_level & G_LOG_FLAG_RECURSION)
474             {
475               /* we use a stack buffer of fixed size, since we're likely
476                * in an out-of-memory situation
477                */
478               gchar buffer[1025];
479               gsize size G_GNUC_UNUSED;
480               va_list args2;
481
482               G_VA_COPY (args2, args1);
483               size = _g_vsnprintf (buffer, 1024, format, args2);
484               va_end (args2);
485
486               log_func (log_domain, test_level, buffer, data);
487             }
488           else
489             {
490               gchar *msg;
491               va_list args2;
492
493               G_VA_COPY (args2, args1);
494               msg = g_strdup_vprintf (format, args2);
495               va_end (args2);
496
497               log_func (log_domain, test_level, msg, data);
498
499               if ((test_level & G_LOG_FLAG_FATAL)
500                 && !(test_level & G_LOG_LEVEL_ERROR))
501                 {
502                   masquerade_fatal = fatal_log_func
503                     && !fatal_log_func (log_domain, test_level, msg, data);
504                 }
505
506               g_free (msg);
507             }
508
509           if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
510             {
511 #ifdef G_OS_WIN32
512               gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
513               
514               MessageBox (NULL, locale_msg, NULL,
515                           MB_ICONERROR|MB_SETFOREGROUND);
516               if (IsDebuggerPresent () && !(test_level & G_LOG_FLAG_RECURSION))
517                 G_BREAKPOINT ();
518               else
519                 abort ();
520 #else
521               if (!(test_level & G_LOG_FLAG_RECURSION))
522                 G_BREAKPOINT ();
523               else
524                 abort ();
525 #endif /* !G_OS_WIN32 */
526             }
527           
528           depth--;
529           g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
530         }
531     }
532 }
533
534 void
535 g_log (const gchar   *log_domain,
536        GLogLevelFlags log_level,
537        const gchar   *format,
538        ...)
539 {
540   va_list args;
541   
542   va_start (args, format);
543   g_logv (log_domain, log_level, format, args);
544   va_end (args);
545 }
546
547 void
548 g_return_if_fail_warning (const char *log_domain,
549                           const char *pretty_function,
550                           const char *expression)
551 {
552   g_log (log_domain,
553          G_LOG_LEVEL_CRITICAL,
554          "%s: assertion `%s' failed",
555          pretty_function,
556          expression);
557 }
558
559 void
560 g_warn_message (const char     *domain,
561                 const char     *file,
562                 int             line,
563                 const char     *func,
564                 const char     *warnexpr)
565 {
566   char *s, lstr[32];
567   g_snprintf (lstr, 32, "%d", line);
568   if (warnexpr)
569     s = g_strconcat ("(", file, ":", lstr, "):",
570                      func, func[0] ? ":" : "",
571                      " runtime check failed: (", warnexpr, ")", NULL);
572   else
573     s = g_strconcat ("(", file, ":", lstr, "):",
574                      func, func[0] ? ":" : "",
575                      " ", "code should not be reached", NULL);
576   g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
577   g_free (s);
578 }
579
580 void
581 g_assert_warning (const char *log_domain,
582                   const char *file,
583                   const int   line,
584                   const char *pretty_function,
585                   const char *expression)
586 {
587   g_log (log_domain,
588          G_LOG_LEVEL_ERROR,
589          expression 
590          ? "file %s: line %d (%s): assertion failed: (%s)"
591          : "file %s: line %d (%s): should not be reached",
592          file, 
593          line, 
594          pretty_function,
595          expression);
596   abort ();
597 }
598
599 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
600                             (wc == 0x7f) || \
601                             (wc >= 0x80 && wc < 0xa0)))
602      
603 static gchar*
604 strdup_convert (const gchar *string,
605                 const gchar *charset)
606 {
607   if (!g_utf8_validate (string, -1, NULL))
608     {
609       GString *gstring = g_string_new ("[Invalid UTF-8] ");
610       guchar *p;
611
612       for (p = (guchar *)string; *p; p++)
613         {
614           if (CHAR_IS_SAFE(*p) &&
615               !(*p == '\r' && *(p + 1) != '\n') &&
616               *p < 0x80)
617             g_string_append_c (gstring, *p);
618           else
619             g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
620         }
621       
622       return g_string_free (gstring, FALSE);
623     }
624   else
625     {
626       GError *err = NULL;
627       
628       gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
629       if (result)
630         return result;
631       else
632         {
633           /* Not thread-safe, but doesn't matter if we print the warning twice
634            */
635           static gboolean warned = FALSE; 
636           if (!warned)
637             {
638               warned = TRUE;
639               _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
640             }
641           g_error_free (err);
642           
643           return g_strdup (string);
644         }
645     }
646 }
647
648 /* For a radix of 8 we need at most 3 output bytes for 1 input
649  * byte. Additionally we might need up to 2 output bytes for the
650  * readix prefix and 1 byte for the trailing NULL.
651  */
652 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
653
654 static void
655 format_unsigned (gchar  *buf,
656                  gulong  num,
657                  guint   radix)
658 {
659   gulong tmp;
660   gchar c;
661   gint i, n;
662
663   /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
664
665   if (radix != 8 && radix != 10 && radix != 16)
666     {
667       *buf = '\000';
668       return;
669     }
670   
671   if (!num)
672     {
673       *buf++ = '0';
674       *buf = '\000';
675       return;
676     } 
677   
678   if (radix == 16)
679     {
680       *buf++ = '0';
681       *buf++ = 'x';
682     }
683   else if (radix == 8)
684     {
685       *buf++ = '0';
686     }
687         
688   n = 0;
689   tmp = num;
690   while (tmp)
691     {
692       tmp /= radix;
693       n++;
694     }
695
696   i = n;
697
698   /* Again we can't use g_assert; actually this check should _never_ fail. */
699   if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
700     {
701       *buf = '\000';
702       return;
703     }
704
705   while (num)
706     {
707       i--;
708       c = (num % radix);
709       if (c < 10)
710         buf[i] = c + '0';
711       else
712         buf[i] = c + 'a' - 10;
713       num /= radix;
714     }
715   
716   buf[n] = '\000';
717 }
718
719 /* string size big enough to hold level prefix */
720 #define STRING_BUFFER_SIZE      (FORMAT_UNSIGNED_BUFSIZE + 32)
721
722 #define ALERT_LEVELS            (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
723
724 static int
725 mklevel_prefix (gchar          level_prefix[STRING_BUFFER_SIZE],
726                 GLogLevelFlags log_level)
727 {
728   gboolean to_stdout = TRUE;
729
730   /* we may not call _any_ GLib functions here */
731
732   switch (log_level & G_LOG_LEVEL_MASK)
733     {
734     case G_LOG_LEVEL_ERROR:
735       strcpy (level_prefix, "ERROR");
736       to_stdout = FALSE;
737       break;
738     case G_LOG_LEVEL_CRITICAL:
739       strcpy (level_prefix, "CRITICAL");
740       to_stdout = FALSE;
741       break;
742     case G_LOG_LEVEL_WARNING:
743       strcpy (level_prefix, "WARNING");
744       to_stdout = FALSE;
745       break;
746     case G_LOG_LEVEL_MESSAGE:
747       strcpy (level_prefix, "Message");
748       to_stdout = FALSE;
749       break;
750     case G_LOG_LEVEL_INFO:
751       strcpy (level_prefix, "INFO");
752       break;
753     case G_LOG_LEVEL_DEBUG:
754       strcpy (level_prefix, "DEBUG");
755       break;
756     default:
757       if (log_level)
758         {
759           strcpy (level_prefix, "LOG-");
760           format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
761         }
762       else
763         strcpy (level_prefix, "LOG");
764       break;
765     }
766   if (log_level & G_LOG_FLAG_RECURSION)
767     strcat (level_prefix, " (recursed)");
768   if (log_level & ALERT_LEVELS)
769     strcat (level_prefix, " **");
770
771 #ifdef G_OS_WIN32
772   win32_keep_fatal_message = (log_level & G_LOG_FLAG_FATAL) != 0;
773 #endif
774   return to_stdout ? 1 : 2;
775 }
776
777 void
778 _g_log_fallback_handler (const gchar   *log_domain,
779                          GLogLevelFlags log_level,
780                          const gchar   *message,
781                          gpointer       unused_data)
782 {
783   gchar level_prefix[STRING_BUFFER_SIZE];
784 #ifndef G_OS_WIN32
785   gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
786 #endif
787   int fd;
788
789   /* we cannot call _any_ GLib functions in this fallback handler,
790    * which is why we skip UTF-8 conversion, etc.
791    * since we either recursed or ran out of memory, we're in a pretty
792    * pathologic situation anyways, what we can do is giving the
793    * the process ID unconditionally however.
794    */
795
796   fd = mklevel_prefix (level_prefix, log_level);
797   if (!message)
798     message = "(NULL) message";
799
800 #ifndef G_OS_WIN32
801   format_unsigned (pid_string, getpid (), 10);
802 #endif
803
804   if (log_domain)
805     write_string (fd, "\n");
806   else
807     write_string (fd, "\n** ");
808
809 #ifndef G_OS_WIN32
810   write_string (fd, "(process:");
811   write_string (fd, pid_string);
812   write_string (fd, "): ");
813 #endif
814
815   if (log_domain)
816     {
817       write_string (fd, log_domain);
818       write_string (fd, "-");
819     }
820   write_string (fd, level_prefix);
821   write_string (fd, ": ");
822   write_string (fd, message);
823 }
824
825 static void
826 escape_string (GString *string)
827 {
828   const char *p = string->str;
829   gunichar wc;
830
831   while (p < string->str + string->len)
832     {
833       gboolean safe;
834             
835       wc = g_utf8_get_char_validated (p, -1);
836       if (wc == (gunichar)-1 || wc == (gunichar)-2)  
837         {
838           gchar *tmp;
839           guint pos;
840
841           pos = p - string->str;
842
843           /* Emit invalid UTF-8 as hex escapes 
844            */
845           tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
846           g_string_erase (string, pos, 1);
847           g_string_insert (string, pos, tmp);
848
849           p = string->str + (pos + 4); /* Skip over escape sequence */
850
851           g_free (tmp);
852           continue;
853         }
854       if (wc == '\r')
855         {
856           safe = *(p + 1) == '\n';
857         }
858       else
859         {
860           safe = CHAR_IS_SAFE (wc);
861         }
862       
863       if (!safe)
864         {
865           gchar *tmp;
866           guint pos;
867
868           pos = p - string->str;
869           
870           /* Largest char we escape is 0x0a, so we don't have to worry
871            * about 8-digit \Uxxxxyyyy
872            */
873           tmp = g_strdup_printf ("\\u%04x", wc); 
874           g_string_erase (string, pos, g_utf8_next_char (p) - p);
875           g_string_insert (string, pos, tmp);
876           g_free (tmp);
877
878           p = string->str + (pos + 6); /* Skip over escape sequence */
879         }
880       else
881         p = g_utf8_next_char (p);
882     }
883 }
884
885 void
886 g_log_default_handler (const gchar   *log_domain,
887                        GLogLevelFlags log_level,
888                        const gchar   *message,
889                        gpointer       unused_data)
890 {
891   gchar level_prefix[STRING_BUFFER_SIZE], *string;
892   GString *gstring;
893   int fd;
894
895   /* we can be called externally with recursion for whatever reason */
896   if (log_level & G_LOG_FLAG_RECURSION)
897     {
898       _g_log_fallback_handler (log_domain, log_level, message, unused_data);
899       return;
900     }
901
902   fd = mklevel_prefix (level_prefix, log_level);
903
904   gstring = g_string_new (NULL);
905   if (log_level & ALERT_LEVELS)
906     g_string_append (gstring, "\n");
907   if (!log_domain)
908     g_string_append (gstring, "** ");
909
910   if ((g_log_msg_prefix & log_level) == log_level)
911     {
912       const gchar *prg_name = g_get_prgname ();
913       
914       if (!prg_name)
915         g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
916       else
917         g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
918     }
919
920   if (log_domain)
921     {
922       g_string_append (gstring, log_domain);
923       g_string_append_c (gstring, '-');
924     }
925   g_string_append (gstring, level_prefix);
926
927   g_string_append (gstring, ": ");
928   if (!message)
929     g_string_append (gstring, "(NULL) message");
930   else
931     {
932       GString *msg;
933       const gchar *charset;
934
935       msg = g_string_new (message);
936       escape_string (msg);
937
938       if (g_get_charset (&charset))
939         g_string_append (gstring, msg->str);    /* charset is UTF-8 already */
940       else
941         {
942           string = strdup_convert (msg->str, charset);
943           g_string_append (gstring, string);
944           g_free (string);
945         }
946
947       g_string_free (msg, TRUE);
948     }
949   g_string_append (gstring, "\n");
950
951   string = g_string_free (gstring, FALSE);
952
953   write_string (fd, string);
954   g_free (string);
955 }
956
957 /**
958  * g_set_print_handler:
959  * @func: the new print handler
960  *
961  * Sets the print handler.
962  *
963  * Any messages passed to g_print() will be output via
964  * the new handler. The default handler simply outputs
965  * the message to stdout. By providing your own handler
966  * you can redirect the output, to a GTK+ widget or a
967  * log file for example.
968  *
969  * Returns: the old print handler
970  */
971 GPrintFunc
972 g_set_print_handler (GPrintFunc func)
973 {
974   GPrintFunc old_print_func;
975
976   g_mutex_lock (&g_messages_lock);
977   old_print_func = glib_print_func;
978   glib_print_func = func;
979   g_mutex_unlock (&g_messages_lock);
980
981   return old_print_func;
982 }
983
984 /**
985  * g_print:
986  * @format: the message format. See the printf() documentation
987  * @...: the parameters to insert into the format string
988  *
989  * Outputs a formatted message via the print handler.
990  * The default print handler simply outputs the message to stdout.
991  *
992  * g_print() should not be used from within libraries for debugging
993  * messages, since it may be redirected by applications to special
994  * purpose message windows or even files. Instead, libraries should
995  * use g_log(), or the convenience functions g_message(), g_warning()
996  * and g_error().
997  */
998 void
999 g_print (const gchar *format,
1000          ...)
1001 {
1002   va_list args;
1003   gchar *string;
1004   GPrintFunc local_glib_print_func;
1005
1006   g_return_if_fail (format != NULL);
1007
1008   va_start (args, format);
1009   string = g_strdup_vprintf (format, args);
1010   va_end (args);
1011
1012   g_mutex_lock (&g_messages_lock);
1013   local_glib_print_func = glib_print_func;
1014   g_mutex_unlock (&g_messages_lock);
1015
1016   if (local_glib_print_func)
1017     local_glib_print_func (string);
1018   else
1019     {
1020       const gchar *charset;
1021
1022       if (g_get_charset (&charset))
1023         fputs (string, stdout); /* charset is UTF-8 already */
1024       else
1025         {
1026           gchar *lstring = strdup_convert (string, charset);
1027
1028           fputs (lstring, stdout);
1029           g_free (lstring);
1030         }
1031       fflush (stdout);
1032     }
1033   g_free (string);
1034 }
1035
1036 /**
1037  * g_set_printerr_handler:
1038  * @func: the new error message handler
1039  *
1040  * Sets the handler for printing error messages.
1041  *
1042  * Any messages passed to g_printerr() will be output via
1043  * the new handler. The default handler simply outputs the
1044  * message to stderr. By providing your own handler you can
1045  * redirect the output, to a GTK+ widget or a log file for
1046  * example.
1047  *
1048  * Returns: the old error message handler
1049  */
1050 GPrintFunc
1051 g_set_printerr_handler (GPrintFunc func)
1052 {
1053   GPrintFunc old_printerr_func;
1054
1055   g_mutex_lock (&g_messages_lock);
1056   old_printerr_func = glib_printerr_func;
1057   glib_printerr_func = func;
1058   g_mutex_unlock (&g_messages_lock);
1059
1060   return old_printerr_func;
1061 }
1062
1063 /**
1064  * g_printerr:
1065  * @format: the message format. See the printf() documentation
1066  * @...: the parameters to insert into the format string
1067  *
1068  * Outputs a formatted message via the error message handler.
1069  * The default handler simply outputs the message to stderr.
1070  *
1071  * g_printerr() should not be used from within libraries.
1072  * Instead g_log() should be used, or the convenience functions
1073  * g_message(), g_warning() and g_error().
1074  */
1075 void
1076 g_printerr (const gchar *format,
1077             ...)
1078 {
1079   va_list args;
1080   gchar *string;
1081   GPrintFunc local_glib_printerr_func;
1082
1083   g_return_if_fail (format != NULL);
1084
1085   va_start (args, format);
1086   string = g_strdup_vprintf (format, args);
1087   va_end (args);
1088
1089   g_mutex_lock (&g_messages_lock);
1090   local_glib_printerr_func = glib_printerr_func;
1091   g_mutex_unlock (&g_messages_lock);
1092
1093   if (local_glib_printerr_func)
1094     local_glib_printerr_func (string);
1095   else
1096     {
1097       const gchar *charset;
1098
1099       if (g_get_charset (&charset))
1100         fputs (string, stderr); /* charset is UTF-8 already */
1101       else
1102         {
1103           gchar *lstring = strdup_convert (string, charset);
1104
1105           fputs (lstring, stderr);
1106           g_free (lstring);
1107         }
1108       fflush (stderr);
1109     }
1110   g_free (string);
1111 }
1112
1113 /**
1114  * g_printf_string_upper_bound:
1115  * @format: the format string. See the printf() documentation
1116  * @args: the parameters to be inserted into the format string
1117  *
1118  * Calculates the maximum space needed to store the output
1119  * of the sprintf() function.
1120  *
1121  * Returns: the maximum space needed to store the formatted string
1122  */
1123 gsize
1124 g_printf_string_upper_bound (const gchar *format,
1125                              va_list      args)
1126 {
1127   gchar c;
1128   return _g_vsnprintf (&c, 1, format, args) + 1;
1129 }