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