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