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