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