on success, close the pipes from the child. Fix from Tim.
[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
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 /* --- prototypes --- */
75 #ifndef HAVE_C99_VSNPRINTF
76 static gsize printf_string_upper_bound (const gchar *format,
77                                         gboolean     may_warn,
78                                         va_list      args);
79 #endif /* !HAVE_C99_VSNPRINTF */
80
81
82 /* --- variables --- */
83 static GMutex        *g_messages_lock = NULL;
84 static GLogDomain    *g_log_domains = NULL;
85 static GLogLevelFlags g_log_always_fatal = G_LOG_FATAL_MASK;
86 static GPrintFunc     glib_print_func = NULL;
87 static GPrintFunc     glib_printerr_func = NULL;
88 static GPrivate      *g_log_depth = NULL;
89 static GLogLevelFlags g_log_msg_prefix = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_DEBUG;
90
91
92 /* --- functions --- */
93 #ifdef G_OS_WIN32
94 #  define STRICT
95 #  include <windows.h>
96 #  undef STRICT
97 #  include <process.h>          /* For _getpid() */
98 static gboolean alloc_console_called = FALSE;
99 static gboolean win32_keep_fatal_message = FALSE;
100
101 /* This default message will usually be overwritten. */
102 /* Yes, a fixed size buffer is bad. So sue me. But g_error is never
103  * with huge strings, is it?
104  */
105 static gchar  fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
106 static gchar *fatal_msg_ptr = fatal_msg_buf;
107
108 /* Just use stdio. If we're out of memory, we're hosed anyway. */
109 #undef write
110 static inline int
111 dowrite (GFileDescriptor fd,
112          const void  *buf,
113          unsigned int len)
114 {
115   if (win32_keep_fatal_message)
116     {
117       memcpy (fatal_msg_ptr, buf, len);
118       fatal_msg_ptr += len;
119       *fatal_msg_ptr = 0;
120       return len;
121     }
122
123   fwrite (buf, len, 1, fd);
124   fflush (fd);
125
126   return len;
127 }
128 #define write(fd, buf, len) dowrite(fd, buf, len)
129
130 static void
131 ensure_stdout_valid (void)
132 {
133   HANDLE handle;
134
135   if (win32_keep_fatal_message)
136     return;
137
138   if (!alloc_console_called)
139     {
140       handle = GetStdHandle (STD_OUTPUT_HANDLE);
141   
142       if (handle == INVALID_HANDLE_VALUE)
143         {
144           AllocConsole ();
145           alloc_console_called = TRUE;
146           freopen ("CONOUT$", "w", stdout);
147         }
148     }
149 }
150 #else
151 #define ensure_stdout_valid()   /* Define as empty */
152 #endif
153
154 static void
155 write_string (GFileDescriptor fd,
156               const gchar    *string)
157 {
158   write (fd, string, strlen (string));
159 }
160
161 static void
162 g_messages_prefixed_init (void)
163 {
164   static gboolean initialized = FALSE;
165
166   if (!initialized)
167     {
168       const gchar *val;
169
170       initialized = TRUE;
171       val = g_getenv ("G_MESSAGES_PREFIXED");
172       
173       if (val)
174         {
175           static const GDebugKey keys[] = {
176             { "error", G_LOG_LEVEL_ERROR },
177             { "critical", G_LOG_LEVEL_CRITICAL },
178             { "warning", G_LOG_LEVEL_WARNING },
179             { "message", G_LOG_LEVEL_MESSAGE },
180             { "info", G_LOG_LEVEL_INFO },
181             { "debug", G_LOG_LEVEL_DEBUG }
182           };
183           
184           g_log_msg_prefix = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
185         }
186     }
187 }
188
189 static GLogDomain*
190 g_log_find_domain_L (const gchar *log_domain)
191 {
192   register GLogDomain *domain;
193   
194   domain = g_log_domains;
195   while (domain)
196     {
197       if (strcmp (domain->log_domain, log_domain) == 0)
198         return domain;
199       domain = domain->next;
200     }
201   return NULL;
202 }
203
204 static GLogDomain*
205 g_log_domain_new_L (const gchar *log_domain)
206 {
207   register GLogDomain *domain;
208
209   domain = g_new (GLogDomain, 1);
210   domain->log_domain = g_strdup (log_domain);
211   domain->fatal_mask = G_LOG_FATAL_MASK;
212   domain->handlers = NULL;
213   
214   domain->next = g_log_domains;
215   g_log_domains = domain;
216   
217   return domain;
218 }
219
220 static void
221 g_log_domain_check_free_L (GLogDomain *domain)
222 {
223   if (domain->fatal_mask == G_LOG_FATAL_MASK &&
224       domain->handlers == NULL)
225     {
226       register GLogDomain *last, *work;
227       
228       last = NULL;  
229
230       work = g_log_domains;
231       while (work)
232         {
233           if (work == domain)
234             {
235               if (last)
236                 last->next = domain->next;
237               else
238                 g_log_domains = domain->next;
239               g_free (domain->log_domain);
240               g_free (domain);
241               break;
242             }
243           last = work;
244           work = last->next;
245         }  
246     }
247 }
248
249 static GLogFunc
250 g_log_domain_get_handler_L (GLogDomain  *domain,
251                             GLogLevelFlags log_level,
252                             gpointer    *data)
253 {
254   if (domain && log_level)
255     {
256       register GLogHandler *handler;
257       
258       handler = domain->handlers;
259       while (handler)
260         {
261           if ((handler->log_level & log_level) == log_level)
262             {
263               *data = handler->data;
264               return handler->log_func;
265             }
266           handler = handler->next;
267         }
268     }
269   return g_log_default_handler;
270 }
271
272 GLogLevelFlags
273 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
274 {
275   GLogLevelFlags old_mask;
276
277   /* restrict the global mask to levels that are known to glib
278    * since this setting applies to all domains
279    */
280   fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
281   /* force errors to be fatal */
282   fatal_mask |= G_LOG_LEVEL_ERROR;
283   /* remove bogus flag */
284   fatal_mask &= ~G_LOG_FLAG_FATAL;
285
286   g_mutex_lock (g_messages_lock);
287   old_mask = g_log_always_fatal;
288   g_log_always_fatal = fatal_mask;
289   g_mutex_unlock (g_messages_lock);
290
291   return old_mask;
292 }
293
294 GLogLevelFlags
295 g_log_set_fatal_mask (const gchar   *log_domain,
296                       GLogLevelFlags fatal_mask)
297 {
298   GLogLevelFlags old_flags;
299   register GLogDomain *domain;
300   
301   if (!log_domain)
302     log_domain = "";
303   
304   /* force errors to be fatal */
305   fatal_mask |= G_LOG_LEVEL_ERROR;
306   /* remove bogus flag */
307   fatal_mask &= ~G_LOG_FLAG_FATAL;
308   
309   g_mutex_lock (g_messages_lock);
310
311   domain = g_log_find_domain_L (log_domain);
312   if (!domain)
313     domain = g_log_domain_new_L (log_domain);
314   old_flags = domain->fatal_mask;
315   
316   domain->fatal_mask = fatal_mask;
317   g_log_domain_check_free_L (domain);
318
319   g_mutex_unlock (g_messages_lock);
320
321   return old_flags;
322 }
323
324 guint
325 g_log_set_handler (const gchar   *log_domain,
326                    GLogLevelFlags log_levels,
327                    GLogFunc       log_func,
328                    gpointer       user_data)
329 {
330   static guint handler_id = 0;
331   GLogDomain *domain;
332   GLogHandler *handler;
333   
334   g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
335   g_return_val_if_fail (log_func != NULL, 0);
336   
337   if (!log_domain)
338     log_domain = "";
339
340   handler = g_new (GLogHandler, 1);
341
342   g_mutex_lock (g_messages_lock);
343
344   domain = g_log_find_domain_L (log_domain);
345   if (!domain)
346     domain = g_log_domain_new_L (log_domain);
347   
348   handler->id = ++handler_id;
349   handler->log_level = log_levels;
350   handler->log_func = log_func;
351   handler->data = user_data;
352   handler->next = domain->handlers;
353   domain->handlers = handler;
354
355   g_mutex_unlock (g_messages_lock);
356   
357   return handler_id;
358 }
359
360 void
361 g_log_remove_handler (const gchar *log_domain,
362                       guint        handler_id)
363 {
364   register GLogDomain *domain;
365   
366   g_return_if_fail (handler_id > 0);
367   
368   if (!log_domain)
369     log_domain = "";
370   
371   g_mutex_lock (g_messages_lock);
372   domain = g_log_find_domain_L (log_domain);
373   if (domain)
374     {
375       GLogHandler *work, *last;
376       
377       last = NULL;
378       work = domain->handlers;
379       while (work)
380         {
381           if (work->id == handler_id)
382             {
383               if (last)
384                 last->next = work->next;
385               else
386                 domain->handlers = work->next;
387               g_log_domain_check_free_L (domain); 
388               g_mutex_unlock (g_messages_lock);
389               g_free (work);
390               return;
391             }
392           last = work;
393           work = last->next;
394         }
395     } 
396   g_mutex_unlock (g_messages_lock);
397   g_warning ("%s: could not find handler with id `%d' for domain \"%s\"",
398              G_STRLOC, handler_id, log_domain);
399 }
400
401 void
402 g_logv (const gchar   *log_domain,
403         GLogLevelFlags log_level,
404         const gchar   *format,
405         va_list        args1)
406 {
407   gchar buffer[1025];
408   gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
409   gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
410   gint i;
411
412 #ifndef  HAVE_VSNPRINTF
413   va_list args2;
414 #endif  /* HAVE_VSNPRINTF */
415   
416   log_level &= G_LOG_LEVEL_MASK;
417   if (!log_level)
418     return;
419   
420   /* we use a stack buffer of fixed size, because we might get called
421    * recursively.
422    */
423 #ifdef  HAVE_VSNPRINTF
424   vsnprintf (buffer, 1024, format, args1);
425 #else   /* !HAVE_VSNPRINTF */
426   G_VA_COPY (args2, args1);
427   if (printf_string_upper_bound (format, FALSE, args1) < 1024)
428     vsprintf (buffer, format, args2);
429   else
430     {
431       /* since we might be out of memory, we can't use g_vsnprintf(). */
432       /* we are out of luck here */
433       strncpy (buffer, format, 1024);
434       buffer[1024] = 0;
435     }
436   va_end (args2);
437 #endif  /* !HAVE_VSNPRINTF */
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               MessageBox (NULL, fatal_msg_buf, 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               fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
552             }
553           g_error_free (err);
554           
555           return g_strdup (string);
556         }
557     }
558 }
559
560 /* For a radix of 8 we need at most 3 output bytes for 1 input
561  * byte. Additionally we might need up to 2 output bytes for the
562  * readix prefix and 1 byte for the trailing NULL.
563  */
564 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
565
566 static void
567 format_unsigned (gchar  *buf,
568                  gulong  num,
569                  guint   radix)
570 {
571   gulong tmp;
572   gchar c;
573   gint i, n;
574
575   /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
576
577   if (radix != 8 && radix != 10 && radix != 16)
578     {
579       *buf = '\000';
580       return;
581     }
582   
583   if (!num)
584     {
585       *buf++ = '0';
586       *buf = '\000';
587       return;
588     } 
589   
590   if (radix == 16)
591     {
592       *buf++ = '0';
593       *buf++ = 'x';
594     }
595   else if (radix == 8)
596     {
597       *buf++ = '0';
598     }
599         
600   n = 0;
601   tmp = num;
602   while (tmp)
603     {
604       tmp /= radix;
605       n++;
606     }
607
608   i = n;
609
610   /* Again we can't use g_assert; actually this check should _never_ fail. */
611   if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
612     {
613       *buf = '\000';
614       return;
615     }
616
617   while (num)
618     {
619       i--;
620       c = (num % radix);
621       if (c < 10)
622         buf[i] = c + '0';
623       else
624         buf[i] = c + 'a' - 10;
625       num /= radix;
626     }
627   
628   buf[n] = '\000';
629 }
630
631 /* string size big enough to hold level prefix */
632 #define STRING_BUFFER_SIZE      (FORMAT_UNSIGNED_BUFSIZE + 32)
633
634 #define ALERT_LEVELS            (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
635
636 static GFileDescriptor
637 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
638                 guint log_level)
639 {
640   gboolean to_stdout = TRUE;
641
642   /* we may not call _any_ GLib functions here */
643
644   switch (log_level & G_LOG_LEVEL_MASK)
645     {
646     case G_LOG_LEVEL_ERROR:
647       strcpy (level_prefix, "ERROR");
648       to_stdout = FALSE;
649       break;
650     case G_LOG_LEVEL_CRITICAL:
651       strcpy (level_prefix, "CRITICAL");
652       to_stdout = FALSE;
653       break;
654     case G_LOG_LEVEL_WARNING:
655       strcpy (level_prefix, "WARNING");
656       to_stdout = FALSE;
657       break;
658     case G_LOG_LEVEL_MESSAGE:
659       strcpy (level_prefix, "Message");
660       to_stdout = FALSE;
661       break;
662     case G_LOG_LEVEL_INFO:
663       strcpy (level_prefix, "INFO");
664       break;
665     case G_LOG_LEVEL_DEBUG:
666       strcpy (level_prefix, "DEBUG");
667       break;
668     default:
669       if (log_level)
670         {
671           strcpy (level_prefix, "LOG-");
672           format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
673         }
674       else
675         strcpy (level_prefix, "LOG");
676       break;
677     }
678   if (log_level & G_LOG_FLAG_RECURSION)
679     strcat (level_prefix, " (recursed)");
680   if (log_level & ALERT_LEVELS)
681     strcat (level_prefix, " **");
682
683   ensure_stdout_valid ();
684 #ifdef G_OS_WIN32
685   win32_keep_fatal_message = (log_level & G_LOG_FLAG_FATAL) != 0;
686   /* Use just stdout as stderr is hard to get redirected from the DOS prompt. */
687   return stdout;
688 #else
689   return to_stdout ? 1 : 2;
690 #endif
691 }
692
693 void
694 _g_log_fallback_handler (const gchar   *log_domain,
695                          GLogLevelFlags log_level,
696                          const gchar   *message,
697                          gpointer       unused_data)
698 {
699   gchar level_prefix[STRING_BUFFER_SIZE], pid_string[FORMAT_UNSIGNED_BUFSIZE];
700   gboolean is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
701   GFileDescriptor fd;
702
703   /* we can not call _any_ GLib functions in this fallback handler,
704    * which is why we skip UTF-8 conversion, etc.
705    * since we either recursed or ran out of memory, we're in a pretty
706    * pathologic situation anyways, what we can do is giving the
707    * the process ID unconditionally however.
708    */
709
710   fd = mklevel_prefix (level_prefix, log_level);
711   if (!message)
712     message = "(NULL) message";
713
714   format_unsigned (pid_string, getpid (), 10);
715
716   if (log_domain)
717     write_string (fd, "\n");
718   else
719     write_string (fd, "\n** ");
720   write_string (fd, "(process:");
721   write_string (fd, pid_string);
722   write_string (fd, "): ");
723   if (log_domain)
724     {
725       write_string (fd, log_domain);
726       write_string (fd, "-");
727     }
728   write_string (fd, level_prefix);
729   write_string (fd, ": ");
730   write_string (fd, message);
731   if (is_fatal)
732     write_string (fd, "\naborting...\n");
733   else
734     write_string (fd, "\n");
735 }
736
737 void
738 g_log_default_handler (const gchar   *log_domain,
739                        GLogLevelFlags log_level,
740                        const gchar   *message,
741                        gpointer       unused_data)
742 {
743   gboolean is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
744   gchar level_prefix[STRING_BUFFER_SIZE], *string;
745   GString *gstring;
746   GFileDescriptor fd;
747
748   /* we can be called externally with recursion for whatever reason */
749   if (log_level & G_LOG_FLAG_RECURSION)
750     {
751       _g_log_fallback_handler (log_domain, log_level, message, unused_data);
752       return;
753     }
754
755   g_messages_prefixed_init ();
756
757   fd = mklevel_prefix (level_prefix, log_level);
758
759   gstring = g_string_new ("");
760   if (log_level & ALERT_LEVELS)
761     g_string_append (gstring, "\n");
762   if (!log_domain)
763     g_string_append (gstring, "** ");
764
765   if ((g_log_msg_prefix & log_level) == log_level)
766     {
767       const gchar *prg_name = g_get_prgname ();
768       
769       if (!prg_name)
770         g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
771       else
772         g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
773     }
774
775   if (log_domain)
776     {
777       g_string_append (gstring, log_domain);
778       g_string_append_c (gstring, '-');
779     }
780   g_string_append (gstring, level_prefix);
781
782   g_string_append (gstring, ": ");
783   if (!message)
784     g_string_append (gstring, "(NULL) message");
785   else
786     {
787       const gchar *charset;
788
789       if (g_get_charset (&charset))
790         g_string_append (gstring, message);     /* charset is UTF-8 already */
791       else
792         {
793           string = strdup_convert (message, charset);
794           g_string_append (gstring, string);
795           g_free (string);
796         }
797     }
798   if (is_fatal)
799     g_string_append (gstring, "\naborting...\n");
800   else
801     g_string_append (gstring, "\n");
802
803   string = g_string_free (gstring, FALSE);
804
805   write_string (fd, string);
806   g_free (string);
807 }
808
809 GPrintFunc
810 g_set_print_handler (GPrintFunc func)
811 {
812   GPrintFunc old_print_func;
813   
814   g_mutex_lock (g_messages_lock);
815   old_print_func = glib_print_func;
816   glib_print_func = func;
817   g_mutex_unlock (g_messages_lock);
818   
819   return old_print_func;
820 }
821
822 void
823 g_print (const gchar *format,
824          ...)
825 {
826   va_list args;
827   gchar *string;
828   GPrintFunc local_glib_print_func;
829   
830   g_return_if_fail (format != NULL);
831   
832   va_start (args, format);
833   string = g_strdup_vprintf (format, args);
834   va_end (args);
835   
836   g_mutex_lock (g_messages_lock);
837   local_glib_print_func = glib_print_func;
838   g_mutex_unlock (g_messages_lock);
839   
840   if (local_glib_print_func)
841     local_glib_print_func (string);
842   else
843     {
844       const gchar *charset;
845
846       ensure_stdout_valid ();
847       if (g_get_charset (&charset))
848         fputs (string, stdout); /* charset is UTF-8 already */
849       else
850         {
851           gchar *lstring = strdup_convert (string, charset);
852
853           fputs (lstring, stdout);
854           g_free (lstring);
855         }
856       fflush (stdout);
857     }
858   g_free (string);
859 }
860
861 GPrintFunc
862 g_set_printerr_handler (GPrintFunc func)
863 {
864   GPrintFunc old_printerr_func;
865   
866   g_mutex_lock (g_messages_lock);
867   old_printerr_func = glib_printerr_func;
868   glib_printerr_func = func;
869   g_mutex_unlock (g_messages_lock);
870   
871   return old_printerr_func;
872 }
873
874 void
875 g_printerr (const gchar *format,
876             ...)
877 {
878   va_list args;
879   gchar *string;
880   GPrintFunc local_glib_printerr_func;
881   
882   g_return_if_fail (format != NULL);
883   
884   va_start (args, format);
885   string = g_strdup_vprintf (format, args);
886   va_end (args);
887   
888   g_mutex_lock (g_messages_lock);
889   local_glib_printerr_func = glib_printerr_func;
890   g_mutex_unlock (g_messages_lock);
891   
892   if (local_glib_printerr_func)
893     local_glib_printerr_func (string);
894   else
895     {
896       const gchar *charset;
897
898       if (g_get_charset (&charset))
899         fputs (string, stderr); /* charset is UTF-8 already */
900       else
901         {
902           gchar *lstring = strdup_convert (string, charset);
903
904           fputs (lstring, stderr);
905           g_free (lstring);
906         }
907       fflush (stderr);
908     }
909   g_free (string);
910 }
911
912 #ifndef MB_LEN_MAX
913 #  define MB_LEN_MAX 8
914 #endif
915
916 #ifndef HAVE_C99_VSNPRINTF
917
918 typedef struct
919 {
920   guint min_width;
921   guint precision;
922   gboolean alternate_format, zero_padding, adjust_left, locale_grouping;
923   gboolean add_space, add_sign, possible_sign, seen_precision;
924   gboolean mod_half, mod_long, mod_extra_long;
925 } PrintfArgSpec;
926
927 static gsize
928 printf_string_upper_bound (const gchar *format,
929                            gboolean     may_warn,
930                            va_list      args)
931 {
932   static const gboolean honour_longs = SIZEOF_LONG > 4 || SIZEOF_VOID_P > 4;
933   gsize len = 1;
934   
935   if (!format)
936     return len;
937   
938   while (*format)
939     {
940       register gchar c = *format++;
941       
942       if (c != '%')
943         len += 1;
944       else /* (c == '%') */
945         {
946           PrintfArgSpec spec = { 0, };
947           gboolean seen_l = FALSE, conv_done = FALSE;
948           gsize conv_len = 0;
949           const gchar *spec_start = format;
950           
951           do
952             {
953               c = *format++;
954               switch (c)
955                 {
956                   GDoubleIEEE754 u_double;
957                   guint v_uint;
958                   gint v_int;
959                   const gchar *v_string;
960                   
961                   /* beware of positional parameters
962                    */
963                 case '$':
964                   if (may_warn)
965                     g_warning (G_GNUC_PRETTY_FUNCTION
966                                "(): unable to handle positional parameters (%%n$)");
967                   len += 1024; /* try adding some safety padding */
968                   conv_done = TRUE;
969                   break;
970                   
971                   /* parse flags
972                    */
973                 case '#':
974                   spec.alternate_format = TRUE;
975                   break;
976                 case '0':
977                   spec.zero_padding = TRUE;
978                   break;
979                 case '-':
980                   spec.adjust_left = TRUE;
981                   break;
982                 case ' ':
983                   spec.add_space = TRUE;
984                   break;
985                 case '+':
986                   spec.add_sign = TRUE;
987                   break;
988                 case '\'':
989                   spec.locale_grouping = TRUE;
990                   break;
991                   
992                   /* parse output size specifications
993                    */
994                 case '.':
995                   spec.seen_precision = TRUE;
996                   break;
997                 case '1':
998                 case '2':
999                 case '3':
1000                 case '4':
1001                 case '5':
1002                 case '6':
1003                 case '7':
1004                 case '8':
1005                 case '9':
1006                   v_uint = c - '0';
1007                   c = *format;
1008                   while (c >= '0' && c <= '9')
1009                     {
1010                       format++;
1011                       v_uint = v_uint * 10 + c - '0';
1012                       c = *format;
1013                     }
1014                   if (spec.seen_precision)
1015                     spec.precision = MAX (spec.precision, v_uint);
1016                   else
1017                     spec.min_width = MAX (spec.min_width, v_uint);
1018                   break;
1019                 case '*':
1020                   v_int = va_arg (args, int);
1021                   if (spec.seen_precision)
1022                     {
1023                       /* forget about negative precision */
1024                       if (v_int >= 0)
1025                         spec.precision = MAX (spec.precision, v_int);
1026                     }
1027                   else
1028                     {
1029                       if (v_int < 0)
1030                         {
1031                           v_int = - v_int;
1032                           spec.adjust_left = TRUE;
1033                         }
1034                       spec.min_width = MAX (spec.min_width, v_int);
1035                     }
1036                   break;
1037                   
1038                   /* parse type modifiers
1039                    */
1040                 case 'h':
1041                   spec.mod_half = TRUE;
1042                   break;
1043                 case 'l':
1044                   if (!seen_l)
1045                     {
1046                       spec.mod_long = TRUE;
1047                       seen_l = TRUE;
1048                       break;
1049                     }
1050                   /* else, fall through */
1051                 case 'L':
1052                 case 'q':
1053                   spec.mod_long = TRUE;
1054                   spec.mod_extra_long = TRUE;
1055                   break;
1056                 case 'z':
1057                 case 'Z':
1058 #if GLIB_SIZEOF_SIZE_T > 4
1059                   spec.mod_long = TRUE;
1060                   spec.mod_extra_long = TRUE;
1061 #endif /* GLIB_SIZEOF_SIZE_T > 4 */
1062                   break;
1063                 case 't':
1064 #if GLIB_SIZEOF_PTRDIFF_T > 4
1065                   spec.mod_long = TRUE;
1066                   spec.mod_extra_long = TRUE;
1067 #endif /* GLIB_SIZEOF_PTRDIFF_T > 4 */
1068                   break;
1069                 case 'j':
1070 #if GLIB_SIZEOF_INTMAX_T > 4
1071                   spec.mod_long = TRUE;
1072                   spec.mod_extra_long = TRUE;
1073 #endif /* GLIB_SIZEOF_INTMAX_T > 4 */
1074                   break;
1075                   
1076                   /* parse output conversions
1077                    */
1078                 case '%':
1079                   conv_len += 1;
1080                   break;
1081                 case 'O':
1082                 case 'D':
1083                 case 'I':
1084                 case 'U':
1085                   /* some C libraries feature long variants for these as well? */
1086                   spec.mod_long = TRUE;
1087                   /* fall through */
1088                 case 'o':
1089                   conv_len += 2;
1090                   /* fall through */
1091                 case 'd':
1092                 case 'i':
1093                   conv_len += 1; /* sign */
1094                   /* fall through */
1095                 case 'u':
1096                   conv_len += 4;
1097                   /* fall through */
1098                 case 'x':
1099                 case 'X':
1100                   spec.possible_sign = TRUE;
1101                   conv_len += 10;
1102                   if (spec.mod_long && honour_longs)
1103                     conv_len *= 2;
1104                   if (spec.mod_extra_long)
1105                     conv_len *= 2;
1106                   if (spec.mod_extra_long)
1107                     {
1108                       (void) va_arg (args, gint64);
1109                     }
1110                   else if (spec.mod_long)
1111                     (void) va_arg (args, long);
1112                   else
1113                     (void) va_arg (args, int);
1114                   break;
1115                 case 'A':
1116                 case 'a':
1117                   /*          0x */
1118                   conv_len += 2;
1119                   /* fall through */
1120                 case 'g':
1121                 case 'G':
1122                 case 'e':
1123                 case 'E':
1124                 case 'f':
1125                   spec.possible_sign = TRUE;
1126                   /*          n   .   dddddddddddddddddddddddd   E   +-  eeee */
1127                   conv_len += 1 + 1 + MAX (24, spec.precision) + 1 + 1 + 4;
1128                   if (may_warn && spec.mod_extra_long)
1129                     g_warning (G_GNUC_PRETTY_FUNCTION
1130                                "(): unable to handle long double, collecting double only");
1131 #ifdef HAVE_LONG_DOUBLE
1132 #error need to implement special handling for long double
1133 #endif
1134                   u_double.v_double = va_arg (args, double);
1135                   /* %f can expand up to all significant digits before '.' (308) */
1136                   if (c == 'f' &&
1137                       u_double.mpn.biased_exponent > 0 && u_double.mpn.biased_exponent < 2047)
1138                     {
1139                       gint exp = u_double.mpn.biased_exponent;
1140                       
1141                       exp -= G_IEEE754_DOUBLE_BIAS;
1142                       exp = exp * G_LOG_2_BASE_10 + 1;
1143                       conv_len += ABS (exp);    /* exp can be <0 */
1144                     }
1145                   /* some printf() implementations require extra padding for rounding */
1146                   conv_len += 2;
1147                   /* we can't really handle locale specific grouping here */
1148                   if (spec.locale_grouping)
1149                     conv_len *= 2;
1150                   break;
1151                 case 'C':
1152                   spec.mod_long = TRUE;
1153                   /* fall through */
1154                 case 'c':
1155                   conv_len += spec.mod_long ? MB_LEN_MAX : 1;
1156                   (void) va_arg (args, int);
1157                   break;
1158                 case 'S':
1159                   spec.mod_long = TRUE;
1160                   /* fall through */
1161                 case 's':
1162                   v_string = va_arg (args, char*);
1163                   if (!v_string)
1164                     conv_len += 8; /* hold "(null)" */
1165                   else if (spec.seen_precision)
1166                     conv_len += spec.precision;
1167                   else
1168                     conv_len += strlen (v_string);
1169                   conv_done = TRUE;
1170                   if (spec.mod_long)
1171                     {
1172                       if (may_warn)
1173                         g_warning (G_GNUC_PRETTY_FUNCTION
1174                                    "(): unable to handle wide char strings");
1175                       len += 1024; /* try adding some safety padding */
1176                     }
1177                   break;
1178                 case 'P': /* do we actually need this? */
1179                   /* fall through */
1180                 case 'p':
1181                   spec.alternate_format = TRUE;
1182                   conv_len += 10;
1183                   if (honour_longs)
1184                     conv_len *= 2;
1185                   /* fall through */
1186                 case 'n':
1187                   conv_done = TRUE;
1188                   (void) va_arg (args, void*);
1189                   break;
1190                 case 'm':
1191                   /* there's not much we can do to be clever */
1192                   v_string = g_strerror (errno);
1193                   v_uint = v_string ? strlen (v_string) : 0;
1194                   conv_len += MAX (256, v_uint);
1195                   break;
1196                   
1197                   /* handle invalid cases
1198                    */
1199                 case '\000':
1200                   /* no conversion specification, bad bad */
1201                   conv_len += format - spec_start;
1202                   break;
1203                 default:
1204                   if (may_warn)
1205                     g_warning (G_GNUC_PRETTY_FUNCTION
1206                                "(): unable to handle `%c' while parsing format",
1207                                c);
1208                   break;
1209                 }
1210               conv_done |= conv_len > 0;
1211             }
1212           while (!conv_done);
1213           /* handle width specifications */
1214           conv_len = MAX (conv_len, MAX (spec.precision, spec.min_width));
1215           /* handle flags */
1216           conv_len += spec.alternate_format ? 2 : 0;
1217           conv_len += (spec.add_space || spec.add_sign || spec.possible_sign);
1218           /* finally done */
1219           len += conv_len;
1220         } /* else (c == '%') */
1221     } /* while (*format) */
1222   
1223   return len;
1224 }
1225
1226 #endif /* !HAVE_C99_VSNPRINTF */
1227
1228
1229 gsize
1230 g_printf_string_upper_bound (const gchar *format,
1231                              va_list      args)
1232 {
1233 #if HAVE_C99_VSNPRINTF
1234   gchar c;
1235   return vsnprintf (&c, 1, format, args) + 1;
1236 #else
1237   return printf_string_upper_bound (format, TRUE, args);
1238 #endif
1239 }
1240
1241 void
1242 g_messages_init (void)
1243 {
1244   g_messages_lock = g_mutex_new ();
1245   g_log_depth = g_private_new (NULL);
1246   g_messages_prefixed_init ();
1247   _g_debug_init ();
1248 }
1249
1250 gboolean _g_debug_initialized = FALSE;
1251 guint _g_debug_flags = 0;
1252
1253 void
1254 _g_debug_init (void) 
1255 {
1256   const gchar *val;
1257   
1258   _g_debug_initialized = TRUE;
1259   
1260   val = g_getenv ("G_DEBUG");
1261   if (val != NULL)
1262     {
1263       static const GDebugKey keys[] = {
1264         {"fatal_warnings", G_DEBUG_FATAL_WARNINGS}
1265       };
1266       
1267       _g_debug_flags = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
1268     }
1269   
1270   if (_g_debug_flags & G_DEBUG_FATAL_WARNINGS) 
1271     {
1272       GLogLevelFlags fatal_mask;
1273       
1274       fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
1275       fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
1276       g_log_set_always_fatal (fatal_mask);
1277     }
1278 }