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