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