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