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