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