Avoid more compiler warnings
[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 "gmessages.h"
45
46 #include "gbacktrace.h"
47 #include "gconvert.h"
48 #include "gdebug.h"
49 #include "gmem.h"
50 #include "gprintfint.h"
51 #include "gtestutils.h"
52 #include "gthread.h"
53 #include "gthreadprivate.h"
54 #include "gstrfuncs.h"
55 #include "gstring.h"
56
57 #ifdef G_OS_WIN32
58 #include <process.h>            /* For getpid() */
59 #include <io.h>
60 #  define STRICT                /* Strict typing, please */
61 #  define _WIN32_WINDOWS 0x0401 /* to get IsDebuggerPresent */
62 #  include <windows.h>
63 #  undef STRICT
64 #endif
65
66
67 /* --- structures --- */
68 typedef struct _GLogDomain      GLogDomain;
69 typedef struct _GLogHandler     GLogHandler;
70 struct _GLogDomain
71 {
72   gchar         *log_domain;
73   GLogLevelFlags fatal_mask;
74   GLogHandler   *handlers;
75   GLogDomain    *next;
76 };
77 struct _GLogHandler
78 {
79   guint          id;
80   GLogLevelFlags log_level;
81   GLogFunc       log_func;
82   gpointer       data;
83   GLogHandler   *next;
84 };
85
86
87 /* --- variables --- */
88 static GMutex        *g_messages_lock = NULL;
89 static GLogDomain    *g_log_domains = NULL;
90 static GLogLevelFlags g_log_always_fatal = G_LOG_FATAL_MASK;
91 static GPrintFunc     glib_print_func = NULL;
92 static GPrintFunc     glib_printerr_func = NULL;
93 static GPrivate      *g_log_depth = NULL;
94 static GLogLevelFlags g_log_msg_prefix = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_DEBUG;
95 static GLogFunc       default_log_func = g_log_default_handler;
96 static gpointer       default_log_data = NULL;
97 static GTestLogFatalFunc fatal_log_func = NULL;
98 static gpointer          fatal_log_data;
99
100 /* --- functions --- */
101 #ifdef G_OS_WIN32
102 #  define STRICT
103 #  include <windows.h>
104 #  undef STRICT
105 static gboolean win32_keep_fatal_message = FALSE;
106
107 /* This default message will usually be overwritten. */
108 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
109  * called with huge strings, is it?
110  */
111 static gchar  fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
112 static gchar *fatal_msg_ptr = fatal_msg_buf;
113
114 #undef write
115 static inline int
116 dowrite (int          fd,
117          const void  *buf,
118          unsigned int len)
119 {
120   if (win32_keep_fatal_message)
121     {
122       memcpy (fatal_msg_ptr, buf, len);
123       fatal_msg_ptr += len;
124       *fatal_msg_ptr = 0;
125       return len;
126     }
127
128   write (fd, buf, len);
129
130   return len;
131 }
132 #define write(fd, buf, len) dowrite(fd, buf, len)
133
134 #endif
135
136 static void
137 write_string (int          fd,
138               const gchar *string)
139 {
140   write (fd, string, strlen (string));
141 }
142
143 static void
144 g_messages_prefixed_init (void)
145 {
146   static gboolean initialized = FALSE;
147
148   if (!initialized)
149     {
150       const gchar *val;
151
152       initialized = TRUE;
153       val = g_getenv ("G_MESSAGES_PREFIXED");
154       
155       if (val)
156         {
157           const GDebugKey keys[] = {
158             { "error", G_LOG_LEVEL_ERROR },
159             { "critical", G_LOG_LEVEL_CRITICAL },
160             { "warning", G_LOG_LEVEL_WARNING },
161             { "message", G_LOG_LEVEL_MESSAGE },
162             { "info", G_LOG_LEVEL_INFO },
163             { "debug", G_LOG_LEVEL_DEBUG }
164           };
165           
166           g_log_msg_prefix = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
167         }
168     }
169 }
170
171 static GLogDomain*
172 g_log_find_domain_L (const gchar *log_domain)
173 {
174   register GLogDomain *domain;
175   
176   domain = g_log_domains;
177   while (domain)
178     {
179       if (strcmp (domain->log_domain, log_domain) == 0)
180         return domain;
181       domain = domain->next;
182     }
183   return NULL;
184 }
185
186 static GLogDomain*
187 g_log_domain_new_L (const gchar *log_domain)
188 {
189   register GLogDomain *domain;
190
191   domain = g_new (GLogDomain, 1);
192   domain->log_domain = g_strdup (log_domain);
193   domain->fatal_mask = G_LOG_FATAL_MASK;
194   domain->handlers = NULL;
195   
196   domain->next = g_log_domains;
197   g_log_domains = domain;
198   
199   return domain;
200 }
201
202 static void
203 g_log_domain_check_free_L (GLogDomain *domain)
204 {
205   if (domain->fatal_mask == G_LOG_FATAL_MASK &&
206       domain->handlers == NULL)
207     {
208       register GLogDomain *last, *work;
209       
210       last = NULL;  
211
212       work = g_log_domains;
213       while (work)
214         {
215           if (work == domain)
216             {
217               if (last)
218                 last->next = domain->next;
219               else
220                 g_log_domains = domain->next;
221               g_free (domain->log_domain);
222               g_free (domain);
223               break;
224             }
225           last = work;
226           work = last->next;
227         }  
228     }
229 }
230
231 static GLogFunc
232 g_log_domain_get_handler_L (GLogDomain  *domain,
233                             GLogLevelFlags log_level,
234                             gpointer    *data)
235 {
236   if (domain && log_level)
237     {
238       register GLogHandler *handler;
239       
240       handler = domain->handlers;
241       while (handler)
242         {
243           if ((handler->log_level & log_level) == log_level)
244             {
245               *data = handler->data;
246               return handler->log_func;
247             }
248           handler = handler->next;
249         }
250     }
251
252   *data = default_log_data;
253   return default_log_func;
254 }
255
256 GLogLevelFlags
257 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
258 {
259   GLogLevelFlags old_mask;
260
261   /* restrict the global mask to levels that are known to glib
262    * since this setting applies to all domains
263    */
264   fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
265   /* force errors to be fatal */
266   fatal_mask |= G_LOG_LEVEL_ERROR;
267   /* remove bogus flag */
268   fatal_mask &= ~G_LOG_FLAG_FATAL;
269
270   g_mutex_lock (g_messages_lock);
271   old_mask = g_log_always_fatal;
272   g_log_always_fatal = fatal_mask;
273   g_mutex_unlock (g_messages_lock);
274
275   return old_mask;
276 }
277
278 GLogLevelFlags
279 g_log_set_fatal_mask (const gchar   *log_domain,
280                       GLogLevelFlags fatal_mask)
281 {
282   GLogLevelFlags old_flags;
283   register GLogDomain *domain;
284   
285   if (!log_domain)
286     log_domain = "";
287   
288   /* force errors to be fatal */
289   fatal_mask |= G_LOG_LEVEL_ERROR;
290   /* remove bogus flag */
291   fatal_mask &= ~G_LOG_FLAG_FATAL;
292   
293   g_mutex_lock (g_messages_lock);
294
295   domain = g_log_find_domain_L (log_domain);
296   if (!domain)
297     domain = g_log_domain_new_L (log_domain);
298   old_flags = domain->fatal_mask;
299   
300   domain->fatal_mask = fatal_mask;
301   g_log_domain_check_free_L (domain);
302
303   g_mutex_unlock (g_messages_lock);
304
305   return old_flags;
306 }
307
308 guint
309 g_log_set_handler (const gchar   *log_domain,
310                    GLogLevelFlags log_levels,
311                    GLogFunc       log_func,
312                    gpointer       user_data)
313 {
314   static guint handler_id = 0;
315   GLogDomain *domain;
316   GLogHandler *handler;
317   
318   g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
319   g_return_val_if_fail (log_func != NULL, 0);
320   
321   if (!log_domain)
322     log_domain = "";
323
324   handler = g_new (GLogHandler, 1);
325
326   g_mutex_lock (g_messages_lock);
327
328   domain = g_log_find_domain_L (log_domain);
329   if (!domain)
330     domain = g_log_domain_new_L (log_domain);
331   
332   handler->id = ++handler_id;
333   handler->log_level = log_levels;
334   handler->log_func = log_func;
335   handler->data = user_data;
336   handler->next = domain->handlers;
337   domain->handlers = handler;
338
339   g_mutex_unlock (g_messages_lock);
340   
341   return handler_id;
342 }
343
344 GLogFunc
345 g_log_set_default_handler (GLogFunc log_func,
346                            gpointer user_data)
347 {
348   GLogFunc old_log_func;
349   
350   g_mutex_lock (g_messages_lock);
351   old_log_func = default_log_func;
352   default_log_func = log_func;
353   default_log_data = user_data;
354   g_mutex_unlock (g_messages_lock);
355   
356   return old_log_func;
357 }
358
359 /**
360  * g_test_log_set_fatal_handler:
361  * @log_func: the log handler function.
362  * @user_data: data passed to the log handler.
363  *
364  * Installs a non-error fatal log handler which can be
365  * used to decide whether log messages which are counted
366  * as fatal abort the program.
367  *
368  * The use case here is that you are running a test case
369  * that depends on particular libraries or circumstances
370  * and cannot prevent certain known critical or warning
371  * messages. So you install a handler that compares the
372  * domain and message to precisely not abort in such a case.
373  *
374  * Note that the handler is reset at the beginning of
375  * any test case, so you have to set it inside each test
376  * function which needs the special behavior.
377  *
378  * This handler has no effect on g_error messages.
379  *
380  * Since: 2.22
381  **/
382 void
383 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
384                               gpointer          user_data)
385 {
386   g_mutex_lock (g_messages_lock);
387   fatal_log_func = log_func;
388   fatal_log_data = user_data;
389   g_mutex_unlock (g_messages_lock);
390 }
391
392 void
393 g_log_remove_handler (const gchar *log_domain,
394                       guint        handler_id)
395 {
396   register GLogDomain *domain;
397   
398   g_return_if_fail (handler_id > 0);
399   
400   if (!log_domain)
401     log_domain = "";
402   
403   g_mutex_lock (g_messages_lock);
404   domain = g_log_find_domain_L (log_domain);
405   if (domain)
406     {
407       GLogHandler *work, *last;
408       
409       last = NULL;
410       work = domain->handlers;
411       while (work)
412         {
413           if (work->id == handler_id)
414             {
415               if (last)
416                 last->next = work->next;
417               else
418                 domain->handlers = work->next;
419               g_log_domain_check_free_L (domain); 
420               g_mutex_unlock (g_messages_lock);
421               g_free (work);
422               return;
423             }
424           last = work;
425           work = last->next;
426         }
427     } 
428   g_mutex_unlock (g_messages_lock);
429   g_warning ("%s: could not find handler with id `%d' for domain \"%s\"",
430              G_STRLOC, handler_id, log_domain);
431 }
432
433 void
434 g_logv (const gchar   *log_domain,
435         GLogLevelFlags log_level,
436         const gchar   *format,
437         va_list        args1)
438 {
439   gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
440   gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
441   gint i;
442
443   log_level &= G_LOG_LEVEL_MASK;
444   if (!log_level)
445     return;
446
447   for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
448     {
449       register GLogLevelFlags test_level;
450
451       test_level = 1 << i;
452       if (log_level & test_level)
453         {
454           guint depth = GPOINTER_TO_UINT (g_private_get (g_log_depth));
455           GLogDomain *domain;
456           GLogFunc log_func;
457           GLogLevelFlags domain_fatal_mask;
458           gpointer data = NULL;
459           gboolean masquerade_fatal = FALSE;
460
461           if (was_fatal)
462             test_level |= G_LOG_FLAG_FATAL;
463           if (was_recursion)
464             test_level |= G_LOG_FLAG_RECURSION;
465
466           /* check recursion and lookup handler */
467           g_mutex_lock (g_messages_lock);
468           domain = g_log_find_domain_L (log_domain ? log_domain : "");
469           if (depth)
470             test_level |= G_LOG_FLAG_RECURSION;
471           depth++;
472           domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
473           if ((domain_fatal_mask | g_log_always_fatal) & test_level)
474             test_level |= G_LOG_FLAG_FATAL;
475           if (test_level & G_LOG_FLAG_RECURSION)
476             log_func = _g_log_fallback_handler;
477           else
478             log_func = g_log_domain_get_handler_L (domain, test_level, &data);
479           domain = NULL;
480           g_mutex_unlock (g_messages_lock);
481
482           g_private_set (g_log_depth, GUINT_TO_POINTER (depth));
483
484           /* had to defer debug initialization until we can keep track of recursion */
485           if (!(test_level & G_LOG_FLAG_RECURSION) && !_g_debug_initialized)
486             {
487               GLogLevelFlags orig_test_level = test_level;
488
489               _g_debug_init ();
490               if ((domain_fatal_mask | g_log_always_fatal) & test_level)
491                 test_level |= G_LOG_FLAG_FATAL;
492               if (test_level != orig_test_level)
493                 {
494                   /* need a relookup, not nice, but not too bad either */
495                   g_mutex_lock (g_messages_lock);
496                   domain = g_log_find_domain_L (log_domain ? log_domain : "");
497                   log_func = g_log_domain_get_handler_L (domain, test_level, &data);
498                   domain = NULL;
499                   g_mutex_unlock (g_messages_lock);
500                 }
501             }
502
503           if (test_level & G_LOG_FLAG_RECURSION)
504             {
505               /* we use a stack buffer of fixed size, since we're likely
506                * in an out-of-memory situation
507                */
508               gchar buffer[1025];
509               gsize size G_GNUC_UNUSED;
510               va_list args2;
511
512               G_VA_COPY (args2, args1);
513               size = _g_vsnprintf (buffer, 1024, format, args2);
514               va_end (args2);
515
516               log_func (log_domain, test_level, buffer, data);
517             }
518           else
519             {
520               gchar *msg;
521               va_list args2;
522
523               G_VA_COPY (args2, args1);
524               msg = g_strdup_vprintf (format, args2);
525               va_end (args2);
526
527               log_func (log_domain, test_level, msg, data);
528
529               if ((test_level & G_LOG_FLAG_FATAL)
530                 && !(test_level & G_LOG_LEVEL_ERROR))
531                 {
532                   masquerade_fatal = fatal_log_func
533                     && !fatal_log_func (log_domain, test_level, msg, data);
534                 }
535
536               g_free (msg);
537             }
538
539           if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
540             {
541 #ifdef G_OS_WIN32
542               gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
543               
544               MessageBox (NULL, locale_msg, NULL,
545                           MB_ICONERROR|MB_SETFOREGROUND);
546               if (IsDebuggerPresent () && !(test_level & G_LOG_FLAG_RECURSION))
547                 G_BREAKPOINT ();
548               else
549                 abort ();
550 #else
551 #if defined (G_ENABLE_DEBUG) && defined (SIGTRAP)
552               if (!(test_level & G_LOG_FLAG_RECURSION))
553                 G_BREAKPOINT ();
554               else
555                 abort ();
556 #else /* !G_ENABLE_DEBUG || !SIGTRAP */
557               abort ();
558 #endif /* !G_ENABLE_DEBUG || !SIGTRAP */
559 #endif /* !G_OS_WIN32 */
560             }
561           
562           depth--;
563           g_private_set (g_log_depth, GUINT_TO_POINTER (depth));
564         }
565     }
566 }
567
568 void
569 g_log (const gchar   *log_domain,
570        GLogLevelFlags log_level,
571        const gchar   *format,
572        ...)
573 {
574   va_list args;
575   
576   va_start (args, format);
577   g_logv (log_domain, log_level, format, args);
578   va_end (args);
579 }
580
581 void
582 g_return_if_fail_warning (const char *log_domain,
583                           const char *pretty_function,
584                           const char *expression)
585 {
586   g_log (log_domain,
587          G_LOG_LEVEL_CRITICAL,
588          "%s: assertion `%s' failed",
589          pretty_function,
590          expression);
591 }
592
593 void
594 g_warn_message (const char     *domain,
595                 const char     *file,
596                 int             line,
597                 const char     *func,
598                 const char     *warnexpr)
599 {
600   char *s, lstr[32];
601   g_snprintf (lstr, 32, "%d", line);
602   if (warnexpr)
603     s = g_strconcat ("(", file, ":", lstr, "):",
604                      func, func[0] ? ":" : "",
605                      " runtime check failed: (", warnexpr, ")", NULL);
606   else
607     s = g_strconcat ("(", file, ":", lstr, "):",
608                      func, func[0] ? ":" : "",
609                      " ", "code should not be reached", NULL);
610   g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
611   g_free (s);
612 }
613
614 void
615 g_assert_warning (const char *log_domain,
616                   const char *file,
617                   const int   line,
618                   const char *pretty_function,
619                   const char *expression)
620 {
621   g_log (log_domain,
622          G_LOG_LEVEL_ERROR,
623          expression 
624          ? "file %s: line %d (%s): assertion failed: (%s)"
625          : "file %s: line %d (%s): should not be reached",
626          file, 
627          line, 
628          pretty_function,
629          expression);
630   abort ();
631 }
632
633 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
634                             (wc == 0x7f) || \
635                             (wc >= 0x80 && wc < 0xa0)))
636      
637 static gchar*
638 strdup_convert (const gchar *string,
639                 const gchar *charset)
640 {
641   if (!g_utf8_validate (string, -1, NULL))
642     {
643       GString *gstring = g_string_new ("[Invalid UTF-8] ");
644       guchar *p;
645
646       for (p = (guchar *)string; *p; p++)
647         {
648           if (CHAR_IS_SAFE(*p) &&
649               !(*p == '\r' && *(p + 1) != '\n') &&
650               *p < 0x80)
651             g_string_append_c (gstring, *p);
652           else
653             g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
654         }
655       
656       return g_string_free (gstring, FALSE);
657     }
658   else
659     {
660       GError *err = NULL;
661       
662       gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
663       if (result)
664         return result;
665       else
666         {
667           /* Not thread-safe, but doesn't matter if we print the warning twice
668            */
669           static gboolean warned = FALSE; 
670           if (!warned)
671             {
672               warned = TRUE;
673               _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
674             }
675           g_error_free (err);
676           
677           return g_strdup (string);
678         }
679     }
680 }
681
682 /* For a radix of 8 we need at most 3 output bytes for 1 input
683  * byte. Additionally we might need up to 2 output bytes for the
684  * readix prefix and 1 byte for the trailing NULL.
685  */
686 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
687
688 static void
689 format_unsigned (gchar  *buf,
690                  gulong  num,
691                  guint   radix)
692 {
693   gulong tmp;
694   gchar c;
695   gint i, n;
696
697   /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
698
699   if (radix != 8 && radix != 10 && radix != 16)
700     {
701       *buf = '\000';
702       return;
703     }
704   
705   if (!num)
706     {
707       *buf++ = '0';
708       *buf = '\000';
709       return;
710     } 
711   
712   if (radix == 16)
713     {
714       *buf++ = '0';
715       *buf++ = 'x';
716     }
717   else if (radix == 8)
718     {
719       *buf++ = '0';
720     }
721         
722   n = 0;
723   tmp = num;
724   while (tmp)
725     {
726       tmp /= radix;
727       n++;
728     }
729
730   i = n;
731
732   /* Again we can't use g_assert; actually this check should _never_ fail. */
733   if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
734     {
735       *buf = '\000';
736       return;
737     }
738
739   while (num)
740     {
741       i--;
742       c = (num % radix);
743       if (c < 10)
744         buf[i] = c + '0';
745       else
746         buf[i] = c + 'a' - 10;
747       num /= radix;
748     }
749   
750   buf[n] = '\000';
751 }
752
753 /* string size big enough to hold level prefix */
754 #define STRING_BUFFER_SIZE      (FORMAT_UNSIGNED_BUFSIZE + 32)
755
756 #define ALERT_LEVELS            (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
757
758 static int
759 mklevel_prefix (gchar          level_prefix[STRING_BUFFER_SIZE],
760                 GLogLevelFlags log_level)
761 {
762   gboolean to_stdout = TRUE;
763
764   /* we may not call _any_ GLib functions here */
765
766   switch (log_level & G_LOG_LEVEL_MASK)
767     {
768     case G_LOG_LEVEL_ERROR:
769       strcpy (level_prefix, "ERROR");
770       to_stdout = FALSE;
771       break;
772     case G_LOG_LEVEL_CRITICAL:
773       strcpy (level_prefix, "CRITICAL");
774       to_stdout = FALSE;
775       break;
776     case G_LOG_LEVEL_WARNING:
777       strcpy (level_prefix, "WARNING");
778       to_stdout = FALSE;
779       break;
780     case G_LOG_LEVEL_MESSAGE:
781       strcpy (level_prefix, "Message");
782       to_stdout = FALSE;
783       break;
784     case G_LOG_LEVEL_INFO:
785       strcpy (level_prefix, "INFO");
786       break;
787     case G_LOG_LEVEL_DEBUG:
788       strcpy (level_prefix, "DEBUG");
789       break;
790     default:
791       if (log_level)
792         {
793           strcpy (level_prefix, "LOG-");
794           format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
795         }
796       else
797         strcpy (level_prefix, "LOG");
798       break;
799     }
800   if (log_level & G_LOG_FLAG_RECURSION)
801     strcat (level_prefix, " (recursed)");
802   if (log_level & ALERT_LEVELS)
803     strcat (level_prefix, " **");
804
805 #ifdef G_OS_WIN32
806   win32_keep_fatal_message = (log_level & G_LOG_FLAG_FATAL) != 0;
807 #endif
808   return to_stdout ? 1 : 2;
809 }
810
811 void
812 _g_log_fallback_handler (const gchar   *log_domain,
813                          GLogLevelFlags log_level,
814                          const gchar   *message,
815                          gpointer       unused_data)
816 {
817   gchar level_prefix[STRING_BUFFER_SIZE];
818 #ifndef G_OS_WIN32
819   gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
820 #endif
821   gboolean is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
822   int fd;
823
824   /* we can not call _any_ GLib functions in this fallback handler,
825    * which is why we skip UTF-8 conversion, etc.
826    * since we either recursed or ran out of memory, we're in a pretty
827    * pathologic situation anyways, what we can do is giving the
828    * the process ID unconditionally however.
829    */
830
831   fd = mklevel_prefix (level_prefix, log_level);
832   if (!message)
833     message = "(NULL) message";
834
835 #ifndef G_OS_WIN32
836   format_unsigned (pid_string, getpid (), 10);
837 #endif
838
839   if (log_domain)
840     write_string (fd, "\n");
841   else
842     write_string (fd, "\n** ");
843
844 #ifndef G_OS_WIN32
845   write_string (fd, "(process:");
846   write_string (fd, pid_string);
847   write_string (fd, "): ");
848 #endif
849
850   if (log_domain)
851     {
852       write_string (fd, log_domain);
853       write_string (fd, "-");
854     }
855   write_string (fd, level_prefix);
856   write_string (fd, ": ");
857   write_string (fd, message);
858   if (is_fatal)
859     write_string (fd, "\naborting...\n");
860   else
861     write_string (fd, "\n");
862 }
863
864 static void
865 escape_string (GString *string)
866 {
867   const char *p = string->str;
868   gunichar wc;
869
870   while (p < string->str + string->len)
871     {
872       gboolean safe;
873             
874       wc = g_utf8_get_char_validated (p, -1);
875       if (wc == (gunichar)-1 || wc == (gunichar)-2)  
876         {
877           gchar *tmp;
878           guint pos;
879
880           pos = p - string->str;
881
882           /* Emit invalid UTF-8 as hex escapes 
883            */
884           tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
885           g_string_erase (string, pos, 1);
886           g_string_insert (string, pos, tmp);
887
888           p = string->str + (pos + 4); /* Skip over escape sequence */
889
890           g_free (tmp);
891           continue;
892         }
893       if (wc == '\r')
894         {
895           safe = *(p + 1) == '\n';
896         }
897       else
898         {
899           safe = CHAR_IS_SAFE (wc);
900         }
901       
902       if (!safe)
903         {
904           gchar *tmp;
905           guint pos;
906
907           pos = p - string->str;
908           
909           /* Largest char we escape is 0x0a, so we don't have to worry
910            * about 8-digit \Uxxxxyyyy
911            */
912           tmp = g_strdup_printf ("\\u%04x", wc); 
913           g_string_erase (string, pos, g_utf8_next_char (p) - p);
914           g_string_insert (string, pos, tmp);
915           g_free (tmp);
916
917           p = string->str + (pos + 6); /* Skip over escape sequence */
918         }
919       else
920         p = g_utf8_next_char (p);
921     }
922 }
923
924 void
925 g_log_default_handler (const gchar   *log_domain,
926                        GLogLevelFlags log_level,
927                        const gchar   *message,
928                        gpointer       unused_data)
929 {
930   gboolean is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
931   gchar level_prefix[STRING_BUFFER_SIZE], *string;
932   GString *gstring;
933   int fd;
934
935   /* we can be called externally with recursion for whatever reason */
936   if (log_level & G_LOG_FLAG_RECURSION)
937     {
938       _g_log_fallback_handler (log_domain, log_level, message, unused_data);
939       return;
940     }
941
942   g_messages_prefixed_init ();
943
944   fd = mklevel_prefix (level_prefix, log_level);
945
946   gstring = g_string_new (NULL);
947   if (log_level & ALERT_LEVELS)
948     g_string_append (gstring, "\n");
949   if (!log_domain)
950     g_string_append (gstring, "** ");
951
952   if ((g_log_msg_prefix & log_level) == log_level)
953     {
954       const gchar *prg_name = g_get_prgname ();
955       
956       if (!prg_name)
957         g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
958       else
959         g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
960     }
961
962   if (log_domain)
963     {
964       g_string_append (gstring, log_domain);
965       g_string_append_c (gstring, '-');
966     }
967   g_string_append (gstring, level_prefix);
968
969   g_string_append (gstring, ": ");
970   if (!message)
971     g_string_append (gstring, "(NULL) message");
972   else
973     {
974       GString *msg;
975       const gchar *charset;
976
977       msg = g_string_new (message);
978       escape_string (msg);
979
980       if (g_get_charset (&charset))
981         g_string_append (gstring, msg->str);    /* charset is UTF-8 already */
982       else
983         {
984           string = strdup_convert (msg->str, charset);
985           g_string_append (gstring, string);
986           g_free (string);
987         }
988
989       g_string_free (msg, TRUE);
990     }
991   if (is_fatal)
992     g_string_append (gstring, "\naborting...\n");
993   else
994     g_string_append (gstring, "\n");
995
996   string = g_string_free (gstring, FALSE);
997
998   write_string (fd, string);
999   g_free (string);
1000 }
1001
1002 GPrintFunc
1003 g_set_print_handler (GPrintFunc func)
1004 {
1005   GPrintFunc old_print_func;
1006   
1007   g_mutex_lock (g_messages_lock);
1008   old_print_func = glib_print_func;
1009   glib_print_func = func;
1010   g_mutex_unlock (g_messages_lock);
1011   
1012   return old_print_func;
1013 }
1014
1015 void
1016 g_print (const gchar *format,
1017          ...)
1018 {
1019   va_list args;
1020   gchar *string;
1021   GPrintFunc local_glib_print_func;
1022   
1023   g_return_if_fail (format != NULL);
1024   
1025   va_start (args, format);
1026   string = g_strdup_vprintf (format, args);
1027   va_end (args);
1028   
1029   g_mutex_lock (g_messages_lock);
1030   local_glib_print_func = glib_print_func;
1031   g_mutex_unlock (g_messages_lock);
1032   
1033   if (local_glib_print_func)
1034     local_glib_print_func (string);
1035   else
1036     {
1037       const gchar *charset;
1038
1039       if (g_get_charset (&charset))
1040         fputs (string, stdout); /* charset is UTF-8 already */
1041       else
1042         {
1043           gchar *lstring = strdup_convert (string, charset);
1044
1045           fputs (lstring, stdout);
1046           g_free (lstring);
1047         }
1048       fflush (stdout);
1049     }
1050   g_free (string);
1051 }
1052
1053 GPrintFunc
1054 g_set_printerr_handler (GPrintFunc func)
1055 {
1056   GPrintFunc old_printerr_func;
1057   
1058   g_mutex_lock (g_messages_lock);
1059   old_printerr_func = glib_printerr_func;
1060   glib_printerr_func = func;
1061   g_mutex_unlock (g_messages_lock);
1062   
1063   return old_printerr_func;
1064 }
1065
1066 void
1067 g_printerr (const gchar *format,
1068             ...)
1069 {
1070   va_list args;
1071   gchar *string;
1072   GPrintFunc local_glib_printerr_func;
1073   
1074   g_return_if_fail (format != NULL);
1075   
1076   va_start (args, format);
1077   string = g_strdup_vprintf (format, args);
1078   va_end (args);
1079   
1080   g_mutex_lock (g_messages_lock);
1081   local_glib_printerr_func = glib_printerr_func;
1082   g_mutex_unlock (g_messages_lock);
1083   
1084   if (local_glib_printerr_func)
1085     local_glib_printerr_func (string);
1086   else
1087     {
1088       const gchar *charset;
1089
1090       if (g_get_charset (&charset))
1091         fputs (string, stderr); /* charset is UTF-8 already */
1092       else
1093         {
1094           gchar *lstring = strdup_convert (string, charset);
1095
1096           fputs (lstring, stderr);
1097           g_free (lstring);
1098         }
1099       fflush (stderr);
1100     }
1101   g_free (string);
1102 }
1103
1104 gsize
1105 g_printf_string_upper_bound (const gchar *format,
1106                              va_list      args)
1107 {
1108   gchar c;
1109   return _g_vsnprintf (&c, 1, format, args) + 1;
1110 }
1111
1112 void
1113 _g_messages_thread_init_nomessage (void)
1114 {
1115   g_messages_lock = g_mutex_new ();
1116   g_log_depth = g_private_new (NULL);
1117   g_messages_prefixed_init ();
1118   _g_debug_init ();
1119 }
1120
1121 gboolean _g_debug_initialized = FALSE;
1122 guint _g_debug_flags = 0;
1123
1124 void
1125 _g_debug_init (void) 
1126 {
1127   const gchar *val;
1128   
1129   _g_debug_initialized = TRUE;
1130   
1131   val = g_getenv ("G_DEBUG");
1132   if (val != NULL)
1133     {
1134       const GDebugKey keys[] = {
1135         {"fatal_warnings", G_DEBUG_FATAL_WARNINGS},
1136         {"fatal_criticals", G_DEBUG_FATAL_CRITICALS}
1137       };
1138       
1139       _g_debug_flags = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
1140     }
1141   
1142   if (_g_debug_flags & G_DEBUG_FATAL_WARNINGS) 
1143     {
1144       GLogLevelFlags fatal_mask;
1145       
1146       fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
1147       fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
1148       g_log_set_always_fatal (fatal_mask);
1149     }
1150   
1151   if (_g_debug_flags & G_DEBUG_FATAL_CRITICALS) 
1152     {
1153       GLogLevelFlags fatal_mask;
1154       
1155       fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
1156       fatal_mask |= G_LOG_LEVEL_CRITICAL;
1157       g_log_set_always_fatal (fatal_mask);
1158     }
1159 }