[Win32] Make the fatal error message box easier to notice with
[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,
514                           MB_ICONERROR|MB_SETFOREGROUND);
515 #endif
516 #if defined (G_ENABLE_DEBUG) && (defined (SIGTRAP) || defined (G_OS_WIN32))
517               if (!(test_level & G_LOG_FLAG_RECURSION))
518                 G_BREAKPOINT ();
519               else
520                 abort ();
521 #else /* !G_ENABLE_DEBUG || !(SIGTRAP || G_OS_WIN32) */
522               abort ();
523 #endif /* !G_ENABLE_DEBUG || !(SIGTRAP || G_OS_WIN32) */
524             }
525           
526           depth--;
527           g_private_set (g_log_depth, GUINT_TO_POINTER (depth));
528         }
529     }
530 }
531
532 void
533 g_log (const gchar   *log_domain,
534        GLogLevelFlags log_level,
535        const gchar   *format,
536        ...)
537 {
538   va_list args;
539   
540   va_start (args, format);
541   g_logv (log_domain, log_level, format, args);
542   va_end (args);
543 }
544
545 static gchar*
546 strdup_convert (const gchar *string,
547                 const gchar *charset)
548 {
549   if (!g_utf8_validate (string, -1, NULL))
550     return g_strconcat ("[Invalid UTF-8] ", string, NULL);
551   else
552     {
553       GError *err = NULL;
554       
555       gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
556       if (result)
557         return result;
558       else
559         {
560           /* Not thread-safe, but doesn't matter if we print the warning twice
561            */
562           static gboolean warned = FALSE; 
563           if (!warned)
564             {
565               warned = TRUE;
566               ensure_stderr_valid ();
567               _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
568             }
569           g_error_free (err);
570           
571           return g_strdup (string);
572         }
573     }
574 }
575
576 /* For a radix of 8 we need at most 3 output bytes for 1 input
577  * byte. Additionally we might need up to 2 output bytes for the
578  * readix prefix and 1 byte for the trailing NULL.
579  */
580 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
581
582 static void
583 format_unsigned (gchar  *buf,
584                  gulong  num,
585                  guint   radix)
586 {
587   gulong tmp;
588   gchar c;
589   gint i, n;
590
591   /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
592
593   if (radix != 8 && radix != 10 && radix != 16)
594     {
595       *buf = '\000';
596       return;
597     }
598   
599   if (!num)
600     {
601       *buf++ = '0';
602       *buf = '\000';
603       return;
604     } 
605   
606   if (radix == 16)
607     {
608       *buf++ = '0';
609       *buf++ = 'x';
610     }
611   else if (radix == 8)
612     {
613       *buf++ = '0';
614     }
615         
616   n = 0;
617   tmp = num;
618   while (tmp)
619     {
620       tmp /= radix;
621       n++;
622     }
623
624   i = n;
625
626   /* Again we can't use g_assert; actually this check should _never_ fail. */
627   if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
628     {
629       *buf = '\000';
630       return;
631     }
632
633   while (num)
634     {
635       i--;
636       c = (num % radix);
637       if (c < 10)
638         buf[i] = c + '0';
639       else
640         buf[i] = c + 'a' - 10;
641       num /= radix;
642     }
643   
644   buf[n] = '\000';
645 }
646
647 /* string size big enough to hold level prefix */
648 #define STRING_BUFFER_SIZE      (FORMAT_UNSIGNED_BUFSIZE + 32)
649
650 #define ALERT_LEVELS            (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
651
652 static GFileDescriptor
653 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
654                 guint log_level)
655 {
656   gboolean to_stdout = TRUE;
657
658   /* we may not call _any_ GLib functions here */
659
660   switch (log_level & G_LOG_LEVEL_MASK)
661     {
662     case G_LOG_LEVEL_ERROR:
663       strcpy (level_prefix, "ERROR");
664       to_stdout = FALSE;
665       break;
666     case G_LOG_LEVEL_CRITICAL:
667       strcpy (level_prefix, "CRITICAL");
668       to_stdout = FALSE;
669       break;
670     case G_LOG_LEVEL_WARNING:
671       strcpy (level_prefix, "WARNING");
672       to_stdout = FALSE;
673       break;
674     case G_LOG_LEVEL_MESSAGE:
675       strcpy (level_prefix, "Message");
676       to_stdout = FALSE;
677       break;
678     case G_LOG_LEVEL_INFO:
679       strcpy (level_prefix, "INFO");
680       break;
681     case G_LOG_LEVEL_DEBUG:
682       strcpy (level_prefix, "DEBUG");
683       break;
684     default:
685       if (log_level)
686         {
687           strcpy (level_prefix, "LOG-");
688           format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
689         }
690       else
691         strcpy (level_prefix, "LOG");
692       break;
693     }
694   if (log_level & G_LOG_FLAG_RECURSION)
695     strcat (level_prefix, " (recursed)");
696   if (log_level & ALERT_LEVELS)
697     strcat (level_prefix, " **");
698
699 #ifdef G_OS_WIN32
700   win32_keep_fatal_message = (log_level & G_LOG_FLAG_FATAL) != 0;
701
702   if (to_stdout)
703     {
704       ensure_stdout_valid ();
705       return stdout;
706     }
707   else
708     {
709       ensure_stderr_valid ();
710       return stderr;
711     }
712 #else
713   return to_stdout ? 1 : 2;
714 #endif
715 }
716
717 void
718 _g_log_fallback_handler (const gchar   *log_domain,
719                          GLogLevelFlags log_level,
720                          const gchar   *message,
721                          gpointer       unused_data)
722 {
723   gchar level_prefix[STRING_BUFFER_SIZE], pid_string[FORMAT_UNSIGNED_BUFSIZE];
724   gboolean is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
725   GFileDescriptor fd;
726
727   /* we can not call _any_ GLib functions in this fallback handler,
728    * which is why we skip UTF-8 conversion, etc.
729    * since we either recursed or ran out of memory, we're in a pretty
730    * pathologic situation anyways, what we can do is giving the
731    * the process ID unconditionally however.
732    */
733
734   fd = mklevel_prefix (level_prefix, log_level);
735   if (!message)
736     message = "(NULL) message";
737
738   format_unsigned (pid_string, getpid (), 10);
739
740   if (log_domain)
741     write_string (fd, "\n");
742   else
743     write_string (fd, "\n** ");
744   write_string (fd, "(process:");
745   write_string (fd, pid_string);
746   write_string (fd, "): ");
747   if (log_domain)
748     {
749       write_string (fd, log_domain);
750       write_string (fd, "-");
751     }
752   write_string (fd, level_prefix);
753   write_string (fd, ": ");
754   write_string (fd, message);
755   if (is_fatal)
756     write_string (fd, "\naborting...\n");
757   else
758     write_string (fd, "\n");
759 }
760
761 void
762 g_log_default_handler (const gchar   *log_domain,
763                        GLogLevelFlags log_level,
764                        const gchar   *message,
765                        gpointer       unused_data)
766 {
767   gboolean is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
768   gchar level_prefix[STRING_BUFFER_SIZE], *string;
769   GString *gstring;
770   GFileDescriptor fd;
771
772   /* we can be called externally with recursion for whatever reason */
773   if (log_level & G_LOG_FLAG_RECURSION)
774     {
775       _g_log_fallback_handler (log_domain, log_level, message, unused_data);
776       return;
777     }
778
779   g_messages_prefixed_init ();
780
781   fd = mklevel_prefix (level_prefix, log_level);
782
783   gstring = g_string_new (NULL);
784   if (log_level & ALERT_LEVELS)
785     g_string_append (gstring, "\n");
786   if (!log_domain)
787     g_string_append (gstring, "** ");
788
789   if ((g_log_msg_prefix & log_level) == log_level)
790     {
791       const gchar *prg_name = g_get_prgname ();
792       
793       if (!prg_name)
794         g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
795       else
796         g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
797     }
798
799   if (log_domain)
800     {
801       g_string_append (gstring, log_domain);
802       g_string_append_c (gstring, '-');
803     }
804   g_string_append (gstring, level_prefix);
805
806   g_string_append (gstring, ": ");
807   if (!message)
808     g_string_append (gstring, "(NULL) message");
809   else
810     {
811       const gchar *charset;
812
813       if (g_get_charset (&charset))
814         g_string_append (gstring, message);     /* charset is UTF-8 already */
815       else
816         {
817           string = strdup_convert (message, charset);
818           g_string_append (gstring, string);
819           g_free (string);
820         }
821     }
822   if (is_fatal)
823     g_string_append (gstring, "\naborting...\n");
824   else
825     g_string_append (gstring, "\n");
826
827   string = g_string_free (gstring, FALSE);
828
829   write_string (fd, string);
830   g_free (string);
831 }
832
833 GPrintFunc
834 g_set_print_handler (GPrintFunc func)
835 {
836   GPrintFunc old_print_func;
837   
838   g_mutex_lock (g_messages_lock);
839   old_print_func = glib_print_func;
840   glib_print_func = func;
841   g_mutex_unlock (g_messages_lock);
842   
843   return old_print_func;
844 }
845
846 void
847 g_print (const gchar *format,
848          ...)
849 {
850   va_list args;
851   gchar *string;
852   GPrintFunc local_glib_print_func;
853   
854   g_return_if_fail (format != NULL);
855   
856   va_start (args, format);
857   string = g_strdup_vprintf (format, args);
858   va_end (args);
859   
860   g_mutex_lock (g_messages_lock);
861   local_glib_print_func = glib_print_func;
862   g_mutex_unlock (g_messages_lock);
863   
864   if (local_glib_print_func)
865     local_glib_print_func (string);
866   else
867     {
868       const gchar *charset;
869
870       ensure_stdout_valid ();
871       if (g_get_charset (&charset))
872         fputs (string, stdout); /* charset is UTF-8 already */
873       else
874         {
875           gchar *lstring = strdup_convert (string, charset);
876
877           fputs (lstring, stdout);
878           g_free (lstring);
879         }
880       fflush (stdout);
881     }
882   g_free (string);
883 }
884
885 GPrintFunc
886 g_set_printerr_handler (GPrintFunc func)
887 {
888   GPrintFunc old_printerr_func;
889   
890   g_mutex_lock (g_messages_lock);
891   old_printerr_func = glib_printerr_func;
892   glib_printerr_func = func;
893   g_mutex_unlock (g_messages_lock);
894   
895   return old_printerr_func;
896 }
897
898 void
899 g_printerr (const gchar *format,
900             ...)
901 {
902   va_list args;
903   gchar *string;
904   GPrintFunc local_glib_printerr_func;
905   
906   g_return_if_fail (format != NULL);
907   
908   va_start (args, format);
909   string = g_strdup_vprintf (format, args);
910   va_end (args);
911   
912   g_mutex_lock (g_messages_lock);
913   local_glib_printerr_func = glib_printerr_func;
914   g_mutex_unlock (g_messages_lock);
915   
916   if (local_glib_printerr_func)
917     local_glib_printerr_func (string);
918   else
919     {
920       const gchar *charset;
921
922       ensure_stderr_valid ();
923       if (g_get_charset (&charset))
924         fputs (string, stderr); /* charset is UTF-8 already */
925       else
926         {
927           gchar *lstring = strdup_convert (string, charset);
928
929           fputs (lstring, stderr);
930           g_free (lstring);
931         }
932       fflush (stderr);
933     }
934   g_free (string);
935 }
936
937 gsize
938 g_printf_string_upper_bound (const gchar *format,
939                              va_list      args)
940 {
941   gchar c;
942   return _g_vsnprintf (&c, 1, format, args) + 1;
943 }
944
945 void
946 _g_messages_thread_init (void)
947 {
948   g_messages_lock = g_mutex_new ();
949   g_messages_prefixed_init ();
950   _g_debug_init ();
951 }
952
953 void
954 _g_messages_thread_private_init (void)
955 {
956   g_assert (g_log_depth == NULL);
957   g_log_depth = g_private_new (NULL);
958 }
959
960 gboolean _g_debug_initialized = FALSE;
961 guint _g_debug_flags = 0;
962
963 void
964 _g_debug_init (void) 
965 {
966   const gchar *val;
967   
968   _g_debug_initialized = TRUE;
969   
970   val = g_getenv ("G_DEBUG");
971   if (val != NULL)
972     {
973       static const GDebugKey keys[] = {
974         {"fatal_warnings", G_DEBUG_FATAL_WARNINGS}
975       };
976       
977       _g_debug_flags = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
978     }
979   
980   if (_g_debug_flags & G_DEBUG_FATAL_WARNINGS) 
981     {
982       GLogLevelFlags fatal_mask;
983       
984       fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
985       fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
986       g_log_set_always_fatal (fatal_mask);
987     }
988 }