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