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