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