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