337d19a50988b03105a6f2f1e964918edebff433
[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 (!(test_level & G_LOG_FLAG_RECURSION))
552                 G_BREAKPOINT ();
553               else
554                 abort ();
555 #endif /* !G_OS_WIN32 */
556             }
557           
558           depth--;
559           g_private_set (g_log_depth, GUINT_TO_POINTER (depth));
560         }
561     }
562 }
563
564 void
565 g_log (const gchar   *log_domain,
566        GLogLevelFlags log_level,
567        const gchar   *format,
568        ...)
569 {
570   va_list args;
571   
572   va_start (args, format);
573   g_logv (log_domain, log_level, format, args);
574   va_end (args);
575 }
576
577 void
578 g_return_if_fail_warning (const char *log_domain,
579                           const char *pretty_function,
580                           const char *expression)
581 {
582   g_log (log_domain,
583          G_LOG_LEVEL_CRITICAL,
584          "%s: assertion `%s' failed",
585          pretty_function,
586          expression);
587 }
588
589 void
590 g_warn_message (const char     *domain,
591                 const char     *file,
592                 int             line,
593                 const char     *func,
594                 const char     *warnexpr)
595 {
596   char *s, lstr[32];
597   g_snprintf (lstr, 32, "%d", line);
598   if (warnexpr)
599     s = g_strconcat ("(", file, ":", lstr, "):",
600                      func, func[0] ? ":" : "",
601                      " runtime check failed: (", warnexpr, ")", NULL);
602   else
603     s = g_strconcat ("(", file, ":", lstr, "):",
604                      func, func[0] ? ":" : "",
605                      " ", "code should not be reached", NULL);
606   g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
607   g_free (s);
608 }
609
610 void
611 g_assert_warning (const char *log_domain,
612                   const char *file,
613                   const int   line,
614                   const char *pretty_function,
615                   const char *expression)
616 {
617   g_log (log_domain,
618          G_LOG_LEVEL_ERROR,
619          expression 
620          ? "file %s: line %d (%s): assertion failed: (%s)"
621          : "file %s: line %d (%s): should not be reached",
622          file, 
623          line, 
624          pretty_function,
625          expression);
626   abort ();
627 }
628
629 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
630                             (wc == 0x7f) || \
631                             (wc >= 0x80 && wc < 0xa0)))
632      
633 static gchar*
634 strdup_convert (const gchar *string,
635                 const gchar *charset)
636 {
637   if (!g_utf8_validate (string, -1, NULL))
638     {
639       GString *gstring = g_string_new ("[Invalid UTF-8] ");
640       guchar *p;
641
642       for (p = (guchar *)string; *p; p++)
643         {
644           if (CHAR_IS_SAFE(*p) &&
645               !(*p == '\r' && *(p + 1) != '\n') &&
646               *p < 0x80)
647             g_string_append_c (gstring, *p);
648           else
649             g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
650         }
651       
652       return g_string_free (gstring, FALSE);
653     }
654   else
655     {
656       GError *err = NULL;
657       
658       gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
659       if (result)
660         return result;
661       else
662         {
663           /* Not thread-safe, but doesn't matter if we print the warning twice
664            */
665           static gboolean warned = FALSE; 
666           if (!warned)
667             {
668               warned = TRUE;
669               _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
670             }
671           g_error_free (err);
672           
673           return g_strdup (string);
674         }
675     }
676 }
677
678 /* For a radix of 8 we need at most 3 output bytes for 1 input
679  * byte. Additionally we might need up to 2 output bytes for the
680  * readix prefix and 1 byte for the trailing NULL.
681  */
682 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
683
684 static void
685 format_unsigned (gchar  *buf,
686                  gulong  num,
687                  guint   radix)
688 {
689   gulong tmp;
690   gchar c;
691   gint i, n;
692
693   /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
694
695   if (radix != 8 && radix != 10 && radix != 16)
696     {
697       *buf = '\000';
698       return;
699     }
700   
701   if (!num)
702     {
703       *buf++ = '0';
704       *buf = '\000';
705       return;
706     } 
707   
708   if (radix == 16)
709     {
710       *buf++ = '0';
711       *buf++ = 'x';
712     }
713   else if (radix == 8)
714     {
715       *buf++ = '0';
716     }
717         
718   n = 0;
719   tmp = num;
720   while (tmp)
721     {
722       tmp /= radix;
723       n++;
724     }
725
726   i = n;
727
728   /* Again we can't use g_assert; actually this check should _never_ fail. */
729   if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
730     {
731       *buf = '\000';
732       return;
733     }
734
735   while (num)
736     {
737       i--;
738       c = (num % radix);
739       if (c < 10)
740         buf[i] = c + '0';
741       else
742         buf[i] = c + 'a' - 10;
743       num /= radix;
744     }
745   
746   buf[n] = '\000';
747 }
748
749 /* string size big enough to hold level prefix */
750 #define STRING_BUFFER_SIZE      (FORMAT_UNSIGNED_BUFSIZE + 32)
751
752 #define ALERT_LEVELS            (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
753
754 static int
755 mklevel_prefix (gchar          level_prefix[STRING_BUFFER_SIZE],
756                 GLogLevelFlags log_level)
757 {
758   gboolean to_stdout = TRUE;
759
760   /* we may not call _any_ GLib functions here */
761
762   switch (log_level & G_LOG_LEVEL_MASK)
763     {
764     case G_LOG_LEVEL_ERROR:
765       strcpy (level_prefix, "ERROR");
766       to_stdout = FALSE;
767       break;
768     case G_LOG_LEVEL_CRITICAL:
769       strcpy (level_prefix, "CRITICAL");
770       to_stdout = FALSE;
771       break;
772     case G_LOG_LEVEL_WARNING:
773       strcpy (level_prefix, "WARNING");
774       to_stdout = FALSE;
775       break;
776     case G_LOG_LEVEL_MESSAGE:
777       strcpy (level_prefix, "Message");
778       to_stdout = FALSE;
779       break;
780     case G_LOG_LEVEL_INFO:
781       strcpy (level_prefix, "INFO");
782       break;
783     case G_LOG_LEVEL_DEBUG:
784       strcpy (level_prefix, "DEBUG");
785       break;
786     default:
787       if (log_level)
788         {
789           strcpy (level_prefix, "LOG-");
790           format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
791         }
792       else
793         strcpy (level_prefix, "LOG");
794       break;
795     }
796   if (log_level & G_LOG_FLAG_RECURSION)
797     strcat (level_prefix, " (recursed)");
798   if (log_level & ALERT_LEVELS)
799     strcat (level_prefix, " **");
800
801 #ifdef G_OS_WIN32
802   win32_keep_fatal_message = (log_level & G_LOG_FLAG_FATAL) != 0;
803 #endif
804   return to_stdout ? 1 : 2;
805 }
806
807 void
808 _g_log_fallback_handler (const gchar   *log_domain,
809                          GLogLevelFlags log_level,
810                          const gchar   *message,
811                          gpointer       unused_data)
812 {
813   gchar level_prefix[STRING_BUFFER_SIZE];
814 #ifndef G_OS_WIN32
815   gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
816 #endif
817   int fd;
818
819   /* we cannot call _any_ GLib functions in this fallback handler,
820    * which is why we skip UTF-8 conversion, etc.
821    * since we either recursed or ran out of memory, we're in a pretty
822    * pathologic situation anyways, what we can do is giving the
823    * the process ID unconditionally however.
824    */
825
826   fd = mklevel_prefix (level_prefix, log_level);
827   if (!message)
828     message = "(NULL) message";
829
830 #ifndef G_OS_WIN32
831   format_unsigned (pid_string, getpid (), 10);
832 #endif
833
834   if (log_domain)
835     write_string (fd, "\n");
836   else
837     write_string (fd, "\n** ");
838
839 #ifndef G_OS_WIN32
840   write_string (fd, "(process:");
841   write_string (fd, pid_string);
842   write_string (fd, "): ");
843 #endif
844
845   if (log_domain)
846     {
847       write_string (fd, log_domain);
848       write_string (fd, "-");
849     }
850   write_string (fd, level_prefix);
851   write_string (fd, ": ");
852   write_string (fd, message);
853 }
854
855 static void
856 escape_string (GString *string)
857 {
858   const char *p = string->str;
859   gunichar wc;
860
861   while (p < string->str + string->len)
862     {
863       gboolean safe;
864             
865       wc = g_utf8_get_char_validated (p, -1);
866       if (wc == (gunichar)-1 || wc == (gunichar)-2)  
867         {
868           gchar *tmp;
869           guint pos;
870
871           pos = p - string->str;
872
873           /* Emit invalid UTF-8 as hex escapes 
874            */
875           tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
876           g_string_erase (string, pos, 1);
877           g_string_insert (string, pos, tmp);
878
879           p = string->str + (pos + 4); /* Skip over escape sequence */
880
881           g_free (tmp);
882           continue;
883         }
884       if (wc == '\r')
885         {
886           safe = *(p + 1) == '\n';
887         }
888       else
889         {
890           safe = CHAR_IS_SAFE (wc);
891         }
892       
893       if (!safe)
894         {
895           gchar *tmp;
896           guint pos;
897
898           pos = p - string->str;
899           
900           /* Largest char we escape is 0x0a, so we don't have to worry
901            * about 8-digit \Uxxxxyyyy
902            */
903           tmp = g_strdup_printf ("\\u%04x", wc); 
904           g_string_erase (string, pos, g_utf8_next_char (p) - p);
905           g_string_insert (string, pos, tmp);
906           g_free (tmp);
907
908           p = string->str + (pos + 6); /* Skip over escape sequence */
909         }
910       else
911         p = g_utf8_next_char (p);
912     }
913 }
914
915 void
916 g_log_default_handler (const gchar   *log_domain,
917                        GLogLevelFlags log_level,
918                        const gchar   *message,
919                        gpointer       unused_data)
920 {
921   gchar level_prefix[STRING_BUFFER_SIZE], *string;
922   GString *gstring;
923   int fd;
924
925   /* we can be called externally with recursion for whatever reason */
926   if (log_level & G_LOG_FLAG_RECURSION)
927     {
928       _g_log_fallback_handler (log_domain, log_level, message, unused_data);
929       return;
930     }
931
932   g_messages_prefixed_init ();
933
934   fd = mklevel_prefix (level_prefix, log_level);
935
936   gstring = g_string_new (NULL);
937   if (log_level & ALERT_LEVELS)
938     g_string_append (gstring, "\n");
939   if (!log_domain)
940     g_string_append (gstring, "** ");
941
942   if ((g_log_msg_prefix & log_level) == log_level)
943     {
944       const gchar *prg_name = g_get_prgname ();
945       
946       if (!prg_name)
947         g_string_append_printf (gstring, "(process:%lu): ", (gulong)getpid ());
948       else
949         g_string_append_printf (gstring, "(%s:%lu): ", prg_name, (gulong)getpid ());
950     }
951
952   if (log_domain)
953     {
954       g_string_append (gstring, log_domain);
955       g_string_append_c (gstring, '-');
956     }
957   g_string_append (gstring, level_prefix);
958
959   g_string_append (gstring, ": ");
960   if (!message)
961     g_string_append (gstring, "(NULL) message");
962   else
963     {
964       GString *msg;
965       const gchar *charset;
966
967       msg = g_string_new (message);
968       escape_string (msg);
969
970       if (g_get_charset (&charset))
971         g_string_append (gstring, msg->str);    /* charset is UTF-8 already */
972       else
973         {
974           string = strdup_convert (msg->str, charset);
975           g_string_append (gstring, string);
976           g_free (string);
977         }
978
979       g_string_free (msg, TRUE);
980     }
981   g_string_append (gstring, "\n");
982
983   string = g_string_free (gstring, FALSE);
984
985   write_string (fd, string);
986   g_free (string);
987 }
988
989 GPrintFunc
990 g_set_print_handler (GPrintFunc func)
991 {
992   GPrintFunc old_print_func;
993   
994   g_mutex_lock (g_messages_lock);
995   old_print_func = glib_print_func;
996   glib_print_func = func;
997   g_mutex_unlock (g_messages_lock);
998   
999   return old_print_func;
1000 }
1001
1002 void
1003 g_print (const gchar *format,
1004          ...)
1005 {
1006   va_list args;
1007   gchar *string;
1008   GPrintFunc local_glib_print_func;
1009   
1010   g_return_if_fail (format != NULL);
1011   
1012   va_start (args, format);
1013   string = g_strdup_vprintf (format, args);
1014   va_end (args);
1015   
1016   g_mutex_lock (g_messages_lock);
1017   local_glib_print_func = glib_print_func;
1018   g_mutex_unlock (g_messages_lock);
1019   
1020   if (local_glib_print_func)
1021     local_glib_print_func (string);
1022   else
1023     {
1024       const gchar *charset;
1025
1026       if (g_get_charset (&charset))
1027         fputs (string, stdout); /* charset is UTF-8 already */
1028       else
1029         {
1030           gchar *lstring = strdup_convert (string, charset);
1031
1032           fputs (lstring, stdout);
1033           g_free (lstring);
1034         }
1035       fflush (stdout);
1036     }
1037   g_free (string);
1038 }
1039
1040 GPrintFunc
1041 g_set_printerr_handler (GPrintFunc func)
1042 {
1043   GPrintFunc old_printerr_func;
1044   
1045   g_mutex_lock (g_messages_lock);
1046   old_printerr_func = glib_printerr_func;
1047   glib_printerr_func = func;
1048   g_mutex_unlock (g_messages_lock);
1049   
1050   return old_printerr_func;
1051 }
1052
1053 void
1054 g_printerr (const gchar *format,
1055             ...)
1056 {
1057   va_list args;
1058   gchar *string;
1059   GPrintFunc local_glib_printerr_func;
1060   
1061   g_return_if_fail (format != NULL);
1062   
1063   va_start (args, format);
1064   string = g_strdup_vprintf (format, args);
1065   va_end (args);
1066   
1067   g_mutex_lock (g_messages_lock);
1068   local_glib_printerr_func = glib_printerr_func;
1069   g_mutex_unlock (g_messages_lock);
1070   
1071   if (local_glib_printerr_func)
1072     local_glib_printerr_func (string);
1073   else
1074     {
1075       const gchar *charset;
1076
1077       if (g_get_charset (&charset))
1078         fputs (string, stderr); /* charset is UTF-8 already */
1079       else
1080         {
1081           gchar *lstring = strdup_convert (string, charset);
1082
1083           fputs (lstring, stderr);
1084           g_free (lstring);
1085         }
1086       fflush (stderr);
1087     }
1088   g_free (string);
1089 }
1090
1091 gsize
1092 g_printf_string_upper_bound (const gchar *format,
1093                              va_list      args)
1094 {
1095   gchar c;
1096   return _g_vsnprintf (&c, 1, format, args) + 1;
1097 }
1098
1099 void
1100 _g_messages_thread_init_nomessage (void)
1101 {
1102   g_messages_lock = g_mutex_new ();
1103   g_log_depth = g_private_new (NULL);
1104   g_messages_prefixed_init ();
1105   _g_debug_init ();
1106 }
1107
1108 gboolean _g_debug_initialized = FALSE;
1109 guint _g_debug_flags = 0;
1110
1111 void
1112 _g_debug_init (void) 
1113 {
1114   const gchar *val;
1115   
1116   _g_debug_initialized = TRUE;
1117   
1118   val = g_getenv ("G_DEBUG");
1119   if (val != NULL)
1120     {
1121       const GDebugKey keys[] = {
1122         {"fatal_warnings", G_DEBUG_FATAL_WARNINGS},
1123         {"fatal_criticals", G_DEBUG_FATAL_CRITICALS}
1124       };
1125       
1126       _g_debug_flags = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
1127     }
1128   
1129   if (_g_debug_flags & G_DEBUG_FATAL_WARNINGS) 
1130     {
1131       GLogLevelFlags fatal_mask;
1132       
1133       fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
1134       fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
1135       g_log_set_always_fatal (fatal_mask);
1136     }
1137   
1138   if (_g_debug_flags & G_DEBUG_FATAL_CRITICALS) 
1139     {
1140       GLogLevelFlags fatal_mask;
1141       
1142       fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
1143       fatal_mask |= G_LOG_LEVEL_CRITICAL;
1144       g_log_set_always_fatal (fatal_mask);
1145     }
1146 }