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