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