got rid of g_set_error_handler(), g_set_warning_handler(),
[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 #ifdef HAVE_CONFIG_H
32 #include <config.h>
33 #endif
34
35 #include <stdlib.h>
36 #include <stdarg.h>
37 #include <stdio.h>
38 #include <string.h>
39 #include "glib.h"
40 #ifdef HAVE_UNISTD_H
41 #include <unistd.h>
42 #endif
43 #include <signal.h>
44 #include <locale.h>
45 #include <errno.h>
46
47 #ifdef G_OS_WIN32
48 typedef FILE* GFileDescriptor;
49 #else
50 typedef gint GFileDescriptor;
51 #endif
52
53 /* --- structures --- */
54 typedef struct _GLogDomain      GLogDomain;
55 typedef struct _GLogHandler     GLogHandler;
56 struct _GLogDomain
57 {
58   gchar         *log_domain;
59   GLogLevelFlags fatal_mask;
60   GLogHandler   *handlers;
61   GLogDomain    *next;
62 };
63 struct _GLogHandler
64 {
65   guint          id;
66   GLogLevelFlags log_level;
67   GLogFunc       log_func;
68   gpointer       data;
69   GLogHandler   *next;
70 };
71
72
73 /* --- prototypes --- */
74 static gsize printf_string_upper_bound (const gchar *format,
75                                         gboolean     may_warn,
76                                         va_list      args);
77
78
79 /* --- variables --- */
80
81 static GMutex* g_messages_lock = NULL;
82
83 const gchar          *g_log_domain_glib = "GLib";
84 static GLogDomain    *g_log_domains = NULL;
85 static GLogLevelFlags g_log_always_fatal = G_LOG_FATAL_MASK;
86 static GPrintFunc     glib_print_func = NULL;
87 static GPrintFunc     glib_printerr_func = NULL;
88
89 static GPrivate* g_log_depth = NULL;
90
91 /* --- functions --- */
92 #ifdef G_OS_WIN32
93 #  define STRICT
94 #  include <windows.h>
95 #  undef STRICT
96 #  include <process.h>          /* For _getpid() */
97
98 static gboolean alloc_console_called = FALSE;
99
100 static gboolean gonna_abort = FALSE;
101
102 /* This default message will usually be overwritten. */
103 /* Yes, a fixed size buffer is bad. So sue me. But g_error is never
104  * with huge strings, is it? */
105 static char fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
106 static char *fatal_msg_ptr = fatal_msg_buf;
107
108 /* Just use stdio. If we're out of memory, we're hosed anyway. */
109 #undef write
110 static inline int
111 dowrite (GFileDescriptor fd,
112          const void  *buf,
113          unsigned int len)
114 {
115   if (gonna_abort)
116     {
117       memcpy (fatal_msg_ptr, buf, len);
118       fatal_msg_ptr += len;
119       *fatal_msg_ptr = 0;
120       return len;
121     }
122
123   fwrite (buf, len, 1, fd);
124   fflush (fd);
125
126   return len;
127 }
128
129 #define write(fd, buf, len) dowrite(fd, buf, len)
130
131 static void
132 ensure_stdout_valid (void)
133 {
134   HANDLE handle;
135
136   if (gonna_abort)
137     return;
138
139   if (!alloc_console_called)
140     {
141       handle = GetStdHandle (STD_OUTPUT_HANDLE);
142   
143       if (handle == INVALID_HANDLE_VALUE)
144         {
145           AllocConsole ();
146           alloc_console_called = TRUE;
147           freopen ("CONOUT$", "w", stdout);
148         }
149     }
150 }
151 #else
152 #define ensure_stdout_valid()   /* Define as empty */
153 #endif
154
155 static void
156 write_unsigned (GFileDescriptor fd,
157                 gulong          num,
158                 guint           radix)
159 {
160   char buffer[64];
161   gulong tmp;
162   char c;
163   int i, n;
164
165   g_return_if_fail (radix >= 2 && radix <= 36);
166   
167   if (!num)
168     {
169       write (fd, "0", 1);
170       return;
171     } 
172   
173   if (radix == 16)
174     write (fd, "0x", 2);
175   else if (radix == 8)
176     write (fd, "0", 1);
177         
178   n = 0;
179   tmp = num;
180   while (tmp)
181     {
182       tmp /= radix;
183       n++;
184     }
185
186   i = n;
187   while (num)
188     {
189       i--;
190       c = (num % radix);
191       if (c < 10)
192         buffer[i] = c + '0';
193       else
194         buffer[i] = c + 'a' - 10;
195       num /= radix;
196     }
197   
198   write (fd, buffer, n);
199 }
200
201 static void
202 write_string (GFileDescriptor fd,
203               gchar *string)
204 {
205   write (fd, string, strlen (string));
206 }
207
208 static void
209 g_log_write_prefix (GFileDescriptor fd,
210                     GLogLevelFlags mask)
211 {
212   static GLogLevelFlags g_log_msg_prefix = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_DEBUG;
213   static gboolean initialized = FALSE;
214   
215   g_mutex_lock (g_messages_lock);
216
217   if (!initialized)
218     {
219       const gchar *val;
220       initialized = TRUE;
221
222       val = g_getenv ("G_MESSAGES_PREFIXED");
223       
224       if (val)
225         {
226           static const GDebugKey keys[] = {
227             { "error", G_LOG_LEVEL_ERROR },
228             { "critical", G_LOG_LEVEL_CRITICAL },
229             { "warning", G_LOG_LEVEL_WARNING },
230             { "message", G_LOG_LEVEL_MESSAGE },
231             { "info", G_LOG_LEVEL_INFO },
232             { "debug", G_LOG_LEVEL_DEBUG }
233           };
234           
235           g_log_msg_prefix = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
236         }
237     }
238   
239   g_mutex_unlock (g_messages_lock);
240   
241   if ((g_log_msg_prefix & mask) == mask)
242     {
243       gchar *prg_name;
244
245       prg_name = g_get_prgname ();
246
247       if (!prg_name)
248         write_string (fd, "(process:");
249       else
250         {
251           write_string (fd, prg_name);
252           write_string (fd, " (pid:");
253         }
254
255       write_unsigned (fd, getpid (), 10);
256       write_string (fd, "): ");
257     }
258 }
259
260 static inline GLogDomain*
261 g_log_find_domain (const gchar *log_domain)
262 {
263   register GLogDomain *domain;
264   
265   g_mutex_lock (g_messages_lock);
266   domain = g_log_domains;
267   while (domain)
268     {
269       if (strcmp (domain->log_domain, log_domain) == 0)
270         {
271           g_mutex_unlock (g_messages_lock);
272           return domain;
273         }
274       domain = domain->next;
275     }
276   g_mutex_unlock (g_messages_lock);
277   return NULL;
278 }
279
280 static inline GLogDomain*
281 g_log_domain_new (const gchar *log_domain)
282 {
283   register GLogDomain *domain;
284
285   domain = g_new (GLogDomain, 1);
286   domain->log_domain = g_strdup (log_domain);
287   domain->fatal_mask = G_LOG_FATAL_MASK;
288   domain->handlers = NULL;
289   
290   g_mutex_lock (g_messages_lock);
291   domain->next = g_log_domains;
292   g_log_domains = domain;
293   g_mutex_unlock (g_messages_lock);
294   
295   return domain;
296 }
297
298 static inline void
299 g_log_domain_check_free (GLogDomain *domain)
300 {
301   if (domain->fatal_mask == G_LOG_FATAL_MASK &&
302       domain->handlers == NULL)
303     {
304       register GLogDomain *last, *work;
305       
306       last = NULL;  
307
308       g_mutex_lock (g_messages_lock);
309       work = g_log_domains;
310       while (work)
311         {
312           if (work == domain)
313             {
314               if (last)
315                 last->next = domain->next;
316               else
317                 g_log_domains = domain->next;
318               g_free (domain->log_domain);
319               g_free (domain);
320               break;
321             }
322           last = work;
323           work = last->next;
324         }  
325       g_mutex_unlock (g_messages_lock);
326     }
327 }
328
329 static inline GLogFunc
330 g_log_domain_get_handler (GLogDomain    *domain,
331                           GLogLevelFlags log_level,
332                           gpointer      *data)
333 {
334   if (domain && log_level)
335     {
336       register GLogHandler *handler;
337       
338       handler = domain->handlers;
339       while (handler)
340         {
341           if ((handler->log_level & log_level) == log_level)
342             {
343               *data = handler->data;
344               return handler->log_func;
345             }
346           handler = handler->next;
347         }
348     }
349   return g_log_default_handler;
350 }
351
352 GLogLevelFlags
353 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
354 {
355   GLogLevelFlags old_mask;
356
357   /* restrict the global mask to levels that are known to glib */
358   fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
359   /* force errors to be fatal */
360   fatal_mask |= G_LOG_LEVEL_ERROR;
361   /* remove bogus flag */
362   fatal_mask &= ~G_LOG_FLAG_FATAL;
363
364   g_mutex_lock (g_messages_lock);
365   old_mask = g_log_always_fatal;
366   g_log_always_fatal = fatal_mask;
367   g_mutex_unlock (g_messages_lock);
368
369   return old_mask;
370 }
371
372 GLogLevelFlags
373 g_log_set_fatal_mask (const gchar    *log_domain,
374                       GLogLevelFlags  fatal_mask)
375 {
376   GLogLevelFlags old_flags;
377   register GLogDomain *domain;
378   
379   if (!log_domain)
380     log_domain = "";
381   
382   /* force errors to be fatal */
383   fatal_mask |= G_LOG_LEVEL_ERROR;
384   /* remove bogus flag */
385   fatal_mask &= ~G_LOG_FLAG_FATAL;
386   
387   domain = g_log_find_domain (log_domain);
388   if (!domain)
389     domain = g_log_domain_new (log_domain);
390   old_flags = domain->fatal_mask;
391   
392   domain->fatal_mask = fatal_mask;
393   g_log_domain_check_free (domain);
394   
395   return old_flags;
396 }
397
398 guint
399 g_log_set_handler (const gchar    *log_domain,
400                    GLogLevelFlags  log_levels,
401                    GLogFunc        log_func,
402                    gpointer        user_data)
403 {
404   register GLogDomain *domain;
405   register GLogHandler *handler;
406   static guint handler_id = 0;
407   
408   g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
409   g_return_val_if_fail (log_func != NULL, 0);
410   
411   if (!log_domain)
412     log_domain = "";
413   
414   domain = g_log_find_domain (log_domain);
415   if (!domain)
416     domain = g_log_domain_new (log_domain);
417   
418   handler = g_new (GLogHandler, 1);
419   g_mutex_lock (g_messages_lock);
420   handler->id = ++handler_id;
421   g_mutex_unlock (g_messages_lock);
422   handler->log_level = log_levels;
423   handler->log_func = log_func;
424   handler->data = user_data;
425   handler->next = domain->handlers;
426   domain->handlers = handler;
427   
428   return handler_id;
429 }
430
431 void
432 g_log_remove_handler (const gchar *log_domain,
433                       guint        handler_id)
434 {
435   register GLogDomain *domain;
436   
437   g_return_if_fail (handler_id > 0);
438   
439   if (!log_domain)
440     log_domain = "";
441   
442   domain = g_log_find_domain (log_domain);
443   if (domain)
444     {
445       register GLogHandler *work, *last;
446       
447       last = NULL;
448       work = domain->handlers;
449       while (work)
450         {
451           if (work->id == handler_id)
452             {
453               if (last)
454                 last->next = work->next;
455               else
456                 domain->handlers = work->next;
457               g_free (work);
458               g_log_domain_check_free (domain);
459               return;
460             }
461           last = work;
462           work = last->next;
463         }
464     }
465   g_warning ("g_log_remove_handler(): could not find handler with id `%d' for domain \"%s\"",
466              handler_id,
467              log_domain);
468 }
469
470 void
471 g_logv (const gchar   *log_domain,
472         GLogLevelFlags log_level,
473         const gchar   *format,
474         va_list        args1)
475 {
476   va_list args2;
477   gchar buffer[1025];
478   register gint i;
479   
480   log_level &= G_LOG_LEVEL_MASK;
481   if (!log_level)
482     return;
483   
484   /* we use a stack buffer of fixed size, because we might get called
485    * recursively.
486    */
487   G_VA_COPY (args2, args1);
488   if (printf_string_upper_bound (format, FALSE, args1) < 1024)
489     vsprintf (buffer, format, args2);
490   else
491     {
492       /* since we might be out of memory, we can't use g_vsnprintf(). */
493 #ifdef  HAVE_VSNPRINTF
494       vsnprintf (buffer, 1024, format, args2);
495 #else   /* !HAVE_VSNPRINTF */
496       /* we are out of luck here */
497       strncpy (buffer, format, 1024);
498 #endif  /* !HAVE_VSNPRINTF */
499       buffer[1024] = 0;
500     }
501   va_end (args2);
502   
503   for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
504     {
505       register GLogLevelFlags test_level;
506       
507       test_level = 1 << i;
508       if (log_level & test_level)
509         {
510           guint depth = GPOINTER_TO_UINT (g_private_get (g_log_depth));
511           GLogDomain *domain;
512           GLogFunc log_func;
513           gpointer data = NULL;
514           
515           domain = g_log_find_domain (log_domain ? log_domain : "");
516           
517           if (depth)
518             test_level |= G_LOG_FLAG_RECURSION;
519           
520           depth++;
521           g_private_set (g_log_depth, GUINT_TO_POINTER (depth));
522
523           g_mutex_lock (g_messages_lock);
524           if ((((domain ? domain->fatal_mask : G_LOG_FATAL_MASK) | 
525                 g_log_always_fatal) & test_level) != 0)
526             test_level |= G_LOG_FLAG_FATAL;  
527           g_mutex_unlock (g_messages_lock);
528
529           log_func = g_log_domain_get_handler (domain, test_level, &data);
530           log_func (log_domain, test_level, buffer, data);
531           
532           /* *domain can be cluttered now */
533           
534           if (test_level & G_LOG_FLAG_FATAL)
535             {
536 #if defined (G_ENABLE_DEBUG) && defined (SIGTRAP)
537               if (!(test_level & G_LOG_FLAG_RECURSION))
538                 G_BREAKPOINT ();
539               else
540                 abort ();
541 #else /* !G_ENABLE_DEBUG || !SIGTRAP */
542 #ifdef G_OS_WIN32
543               MessageBox (NULL, fatal_msg_buf, NULL, MB_OK);
544 #endif
545 # if defined (_MSC_VER) && defined (_DEBUG)
546               /* let's see the call stack ... */
547               __asm int 3
548 # endif
549               abort ();
550 #endif /* !G_ENABLE_DEBUG || !SIGTRAP */
551             }
552           
553           depth--;
554           g_private_set (g_log_depth, GUINT_TO_POINTER (depth));
555         }
556     }
557 }
558
559 void
560 g_log (const gchar    *log_domain,
561        GLogLevelFlags  log_level,
562        const gchar    *format,
563        ...)
564 {
565   va_list args;
566   
567   va_start (args, format);
568   g_logv (log_domain, log_level, format, args);
569   va_end (args);
570 }
571
572 void
573 g_log_default_handler (const gchar    *log_domain,
574                        GLogLevelFlags  log_level,
575                        const gchar    *message,
576                        gpointer        unused_data)
577 {
578   GFileDescriptor fd;
579   gboolean in_recursion;
580   gboolean is_fatal;  
581   
582   in_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
583   is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
584   log_level &= G_LOG_LEVEL_MASK;
585   
586   if (!message)
587     message = "g_log_default_handler(): (NULL) message";
588   
589 #ifdef G_OS_WIN32
590   /* Use just stdout as stderr is hard to get redirected from the
591    * DOS prompt.
592    */
593   fd = stdout;
594   gonna_abort = is_fatal;
595 #else
596   fd = (log_level > G_LOG_LEVEL_MESSAGE) ? 1 : 2;
597 #endif
598   
599   switch (log_level)
600     {
601     case G_LOG_LEVEL_ERROR:
602       /* use write(2) for output, in case we are out of memeory */
603       ensure_stdout_valid ();
604       write (fd, "\n", 1);
605       g_log_write_prefix (fd, log_level);
606
607       if (log_domain)
608         {
609           write (fd, log_domain, strlen (log_domain));
610           write (fd, "-", 1);
611         }
612       else
613         write (fd, "** ", 3);
614       if (in_recursion)
615         write (fd, "ERROR (recursed) **: ", 21);
616       else
617         write (fd, "ERROR **: ", 10);
618       write (fd, message, strlen (message));
619       if (is_fatal)
620         write (fd, "\naborting...\n", 13);
621       else
622         write (fd, "\n", 1);
623       break;
624     case G_LOG_LEVEL_CRITICAL:
625       ensure_stdout_valid ();
626       write (fd, "\n", 1);
627       g_log_write_prefix (fd, log_level);
628
629       if (log_domain)
630         {
631           write (fd, log_domain, strlen (log_domain));
632           write (fd, "-", 1);
633         }
634       else
635         write (fd, "** ", 3);
636       if (in_recursion)
637         write (fd, "CRITICAL (recursed) **: ", 24);
638       else
639         write (fd, "CRITICAL **: ", 13);
640       write (fd, message, strlen (message));
641       if (is_fatal)
642         write (fd, "\naborting...\n", 13);
643       else
644         write (fd, "\n", 1);
645       break;
646     case G_LOG_LEVEL_WARNING:
647       ensure_stdout_valid ();
648       write (fd, "\n", 1);
649       g_log_write_prefix (fd, log_level);
650
651       if (log_domain)
652         {
653           write (fd, log_domain, strlen (log_domain));
654           write (fd, "-", 1);
655         }
656       else
657         write (fd, "** ", 3);
658       if (in_recursion)
659         write (fd, "WARNING (recursed) **: ", 23);
660       else
661         write (fd, "WARNING **: ", 12);
662       write (fd, message, strlen (message));
663       if (is_fatal)
664         write (fd, "\naborting...\n", 13);
665       else
666         write (fd, "\n", 1);
667       break;
668     case G_LOG_LEVEL_MESSAGE:
669       ensure_stdout_valid ();
670
671       g_log_write_prefix (fd, log_level);
672
673       if (log_domain)
674         {
675           write (fd, log_domain, strlen (log_domain));
676           write (fd, "-", 1);
677         }
678       if (in_recursion)
679         write (fd, "Message (recursed): ", 20);
680       else
681         write (fd, "Message: ", 9);
682       write (fd, message, strlen (message));
683       if (is_fatal)
684         write (fd, "\naborting...\n", 13);
685       else
686         write (fd, "\n", 1);
687       break;
688     case G_LOG_LEVEL_INFO:
689       ensure_stdout_valid ();
690
691       g_log_write_prefix (fd, log_level);
692
693       if (log_domain)
694         {
695           write (fd, log_domain, strlen (log_domain));
696           write (fd, "-", 1);
697         }
698       if (in_recursion)
699         write (fd, "INFO (recursed): ", 17);
700       else
701         write (fd, "INFO: ", 6);
702       write (fd, message, strlen (message));
703       if (is_fatal)
704         write (fd, "\naborting...\n", 13);
705       else
706         write (fd, "\n", 1);
707       break;
708     case G_LOG_LEVEL_DEBUG:
709       ensure_stdout_valid ();
710
711       g_log_write_prefix (fd, log_level);
712
713       if (log_domain)
714         {
715           write (fd, log_domain, strlen (log_domain));
716           write (fd, "-", 1);
717         }
718       if (in_recursion)
719         write (fd, "DEBUG (recursed): ", 18);
720       else
721         write (fd, "DEBUG: ", 7);
722       write (fd, message, strlen (message));
723       if (is_fatal)
724         write (fd, "\naborting...\n", 13);
725       else
726         write (fd, "\n", 1);
727       break;
728     default:
729       /* we are used for a log level that is not defined by GLib itself,
730        * try to make the best out of it.
731        */
732       ensure_stdout_valid ();
733
734       g_log_write_prefix (fd, log_level);
735
736       if (log_domain)
737         {
738           write (fd, log_domain, strlen (log_domain));
739           if (in_recursion)
740             write (fd, "-LOG (recursed:", 15);
741           else
742             write (fd, "-LOG (", 6);
743         }
744       else if (in_recursion)
745         write (fd, "LOG (recursed:", 14);
746       else
747         write (fd, "LOG (", 5);
748       if (log_level)
749         {
750           gchar string[] = "0x00): ";
751           gchar *p = string + 2;
752           guint i;
753           
754           i = g_bit_nth_msf (log_level, -1);
755           *p = i >> 4;
756           p++;
757           *p = '0' + (i & 0xf);
758           if (*p > '9')
759             *p += 'A' - '9' - 1;
760           
761           write (fd, string, 7);
762         }
763       else
764         write (fd, "): ", 3);
765       write (fd, message, strlen (message));
766       if (is_fatal)
767         write (fd, "\naborting...\n", 13);
768       else
769         write (fd, "\n", 1);
770       break;
771     }
772 }
773
774 GPrintFunc
775 g_set_print_handler (GPrintFunc func)
776 {
777   GPrintFunc old_print_func;
778   
779   g_mutex_lock (g_messages_lock);
780   old_print_func = glib_print_func;
781   glib_print_func = func;
782   g_mutex_unlock (g_messages_lock);
783   
784   return old_print_func;
785 }
786
787 void
788 g_print (const gchar *format,
789          ...)
790 {
791   va_list args;
792   gchar *string;
793   GPrintFunc local_glib_print_func;
794   
795   g_return_if_fail (format != NULL);
796   
797   va_start (args, format);
798   string = g_strdup_vprintf (format, args);
799   va_end (args);
800   
801   g_mutex_lock (g_messages_lock);
802   local_glib_print_func = glib_print_func;
803   g_mutex_unlock (g_messages_lock);
804
805   if (local_glib_print_func)
806     local_glib_print_func (string);
807   else
808     {
809       ensure_stdout_valid ();
810       fputs (string, stdout);
811       fflush (stdout);
812     }
813   g_free (string);
814 }
815
816 GPrintFunc
817 g_set_printerr_handler (GPrintFunc func)
818 {
819   GPrintFunc old_printerr_func;
820   
821   g_mutex_lock (g_messages_lock);
822   old_printerr_func = glib_printerr_func;
823   glib_printerr_func = func;
824   g_mutex_unlock (g_messages_lock);
825   
826   return old_printerr_func;
827 }
828
829 void
830 g_printerr (const gchar *format,
831             ...)
832 {
833   va_list args;
834   gchar *string;
835   GPrintFunc local_glib_printerr_func;
836   
837   g_return_if_fail (format != NULL);
838   
839   va_start (args, format);
840   string = g_strdup_vprintf (format, args);
841   va_end (args);
842   
843   g_mutex_lock (g_messages_lock);
844   local_glib_printerr_func = glib_printerr_func;
845   g_mutex_unlock (g_messages_lock);
846
847   if (local_glib_printerr_func)
848     local_glib_printerr_func (string);
849   else
850     {
851       fputs (string, stderr);
852       fflush (stderr);
853     }
854   g_free (string);
855 }
856
857 #ifndef MB_LEN_MAX
858 #  define MB_LEN_MAX 8
859 #endif
860
861 typedef struct
862 {
863   guint min_width;
864   guint precision;
865   gboolean alternate_format, zero_padding, adjust_left, locale_grouping;
866   gboolean add_space, add_sign, possible_sign, seen_precision;
867   gboolean mod_half, mod_long, mod_extra_long;
868 } PrintfArgSpec;
869
870 static gsize
871 printf_string_upper_bound (const gchar *format,
872                            gboolean     may_warn,
873                            va_list      args)
874 {
875   static const gboolean honour_longs = SIZEOF_LONG > 4 || SIZEOF_VOID_P > 4;
876   gsize len = 1;
877
878   if (!format)
879     return len;
880
881   while (*format)
882     {
883       register gchar c = *format++;
884
885       if (c != '%')
886         len += 1;
887       else /* (c == '%') */
888         {
889           PrintfArgSpec spec = { 0, };
890           gboolean seen_l = FALSE, conv_done = FALSE;
891           gsize conv_len = 0;
892           const gchar *spec_start = format;
893
894           do
895             {
896               c = *format++;
897               switch (c)
898                 {
899                   GDoubleIEEE754 u_double;
900                   guint v_uint;
901                   gint v_int;
902                   const gchar *v_string;
903
904                   /* beware of positional parameters
905                    */
906                 case '$':
907                   if (may_warn)
908                     g_warning (G_GNUC_PRETTY_FUNCTION
909                                "(): unable to handle positional parameters (%%n$)");
910                   len += 1024; /* try adding some safety padding */
911                   break;
912
913                   /* parse flags
914                    */
915                 case '#':
916                   spec.alternate_format = TRUE;
917                   break;
918                 case '0':
919                   spec.zero_padding = TRUE;
920                   break;
921                 case '-':
922                   spec.adjust_left = TRUE;
923                   break;
924                 case ' ':
925                   spec.add_space = TRUE;
926                   break;
927                 case '+':
928                   spec.add_sign = TRUE;
929                   break;
930                 case '\'':
931                   spec.locale_grouping = TRUE;
932                   break;
933
934                   /* parse output size specifications
935                    */
936                 case '.':
937                   spec.seen_precision = TRUE;
938                   break;
939                 case '1':
940                 case '2':
941                 case '3':
942                 case '4':
943                 case '5':
944                 case '6':
945                 case '7':
946                 case '8':
947                 case '9':
948                   v_uint = c - '0';
949                   c = *format;
950                   while (c >= '0' && c <= '9')
951                     {
952                       format++;
953                       v_uint = v_uint * 10 + c - '0';
954                       c = *format;
955                     }
956                   if (spec.seen_precision)
957                     spec.precision = MAX (spec.precision, v_uint);
958                   else
959                     spec.min_width = MAX (spec.min_width, v_uint);
960                   break;
961                 case '*':
962                   v_int = va_arg (args, int);
963                   if (spec.seen_precision)
964                     {
965                       /* forget about negative precision */
966                       if (v_int >= 0)
967                         spec.precision = MAX (spec.precision, v_int);
968                     }
969                   else
970                     {
971                       if (v_int < 0)
972                         {
973                           v_int = - v_int;
974                           spec.adjust_left = TRUE;
975                         }
976                       spec.min_width = MAX (spec.min_width, v_int);
977                     }
978                   break;
979
980                   /* parse type modifiers
981                    */
982                 case 'h':
983                   spec.mod_half = TRUE;
984                   break;
985                 case 'l':
986                   if (!seen_l)
987                     {
988                       spec.mod_long = TRUE;
989                       seen_l = TRUE;
990                       break;
991                     }
992                   /* else, fall through */
993                 case 'L':
994                 case 'q':
995                   spec.mod_long = TRUE;
996                   spec.mod_extra_long = TRUE;
997                   break;
998                 case 'z':
999                 case 'Z':
1000 #if GLIB_SIZEOF_SIZE_T > 4
1001                   spec.mod_long = TRUE;
1002                   spec.mod_extra_long = TRUE;
1003 #endif /* GLIB_SIZEOF_SIZE_T > 4 */
1004                   break;
1005                 case 't':
1006 #if GLIB_SIZEOF_PTRDIFF_T > 4
1007                   spec.mod_long = TRUE;
1008                   spec.mod_extra_long = TRUE;
1009 #endif /* GLIB_SIZEOF_PTRDIFF_T > 4 */
1010                   break;
1011                 case 'j':
1012 #if GLIB_SIZEOF_INTMAX_T > 4
1013                   spec.mod_long = TRUE;
1014                   spec.mod_extra_long = TRUE;
1015 #endif /* GLIB_SIZEOF_INTMAX_T > 4 */
1016                   break;
1017
1018                   /* parse output conversions
1019                    */
1020                 case '%':
1021                   conv_len += 1;
1022                   break;
1023                 case 'O':
1024                 case 'D':
1025                 case 'I':
1026                 case 'U':
1027                   /* some C libraries feature long variants for these as well? */
1028                   spec.mod_long = TRUE;
1029                   /* fall through */
1030                 case 'o':
1031                   conv_len += 2;
1032                   /* fall through */
1033                 case 'd':
1034                 case 'i':
1035                   conv_len += 1; /* sign */
1036                   /* fall through */
1037                 case 'u':
1038                   conv_len += 4;
1039                   /* fall through */
1040                 case 'x':
1041                 case 'X':
1042                   spec.possible_sign = TRUE;
1043                   conv_len += 10;
1044                   if (spec.mod_long && honour_longs)
1045                     conv_len *= 2;
1046                   if (spec.mod_extra_long)
1047                     conv_len *= 2;
1048                   if (spec.mod_extra_long)
1049                     {
1050 #ifdef G_HAVE_GINT64
1051                       (void) va_arg (args, gint64);
1052 #else /* !G_HAVE_GINT64 */
1053                       (void) va_arg (args, long);
1054 #endif /* !G_HAVE_GINT64 */
1055                     }
1056                   else if (spec.mod_long)
1057                     (void) va_arg (args, long);
1058                   else
1059                     (void) va_arg (args, int);
1060                   break;
1061                 case 'A':
1062                 case 'a':
1063                   /*          0x */
1064                   conv_len += 2;
1065                   /* fall through */
1066                 case 'g':
1067                 case 'G':
1068                 case 'e':
1069                 case 'E':
1070                 case 'f':
1071                   spec.possible_sign = TRUE;
1072                   /*          n   .   dddddddddddddddddddddddd   E   +-  eeee */
1073                   conv_len += 1 + 1 + MAX (24, spec.precision) + 1 + 1 + 4;
1074                   if (may_warn && spec.mod_extra_long)
1075                     g_warning (G_GNUC_PRETTY_FUNCTION
1076                                "(): unable to handle long double, collecting double only");
1077 #ifdef HAVE_LONG_DOUBLE
1078 #error need to implement special handling for long double
1079 #endif
1080                   u_double.v_double = va_arg (args, double);
1081                   /* %f can expand up to all significant digits before '.' (308) */
1082                   if (c == 'f' &&
1083                       u_double.mpn.biased_exponent > 0 && u_double.mpn.biased_exponent < 2047)
1084                     {
1085                       gint exp = u_double.mpn.biased_exponent;
1086
1087                       exp -= G_IEEE754_DOUBLE_BIAS;
1088                       exp = exp * G_LOG_2_BASE_10 + 1;
1089                       conv_len += ABS (exp);    /* exp can be <0 */
1090                     }
1091                   /* some printf() implementations require extra padding for rounding */
1092                   conv_len += 2;
1093                   /* we can't really handle locale specific grouping here */
1094                   if (spec.locale_grouping)
1095                     conv_len *= 2;
1096                   break;
1097                 case 'C':
1098                   spec.mod_long = TRUE;
1099                   /* fall through */
1100                 case 'c':
1101                   conv_len += spec.mod_long ? MB_LEN_MAX : 1;
1102                   (void) va_arg (args, int);
1103                   break;
1104                 case 'S':
1105                   spec.mod_long = TRUE;
1106                   /* fall through */
1107                 case 's':
1108                   v_string = va_arg (args, char*);
1109                   if (!v_string)
1110                     conv_len += 8; /* hold "(null)" */
1111                   else if (spec.seen_precision)
1112                     conv_len += spec.precision;
1113                   else
1114                     conv_len += strlen (v_string);
1115                   conv_done = TRUE;
1116                   if (spec.mod_long)
1117                     {
1118                       if (may_warn)
1119                         g_warning (G_GNUC_PRETTY_FUNCTION
1120                                    "(): unable to handle wide char strings");
1121                       len += 1024; /* try adding some safety padding */
1122                     }
1123                   break;
1124                 case 'P': /* do we actually need this? */
1125                   /* fall through */
1126                 case 'p':
1127                   spec.alternate_format = TRUE;
1128                   conv_len += 10;
1129                   if (honour_longs)
1130                     conv_len *= 2;
1131                   /* fall through */
1132                 case 'n':
1133                   conv_done = TRUE;
1134                   (void) va_arg (args, void*);
1135                   break;
1136                 case 'm':
1137                   /* there's not much we can do to be clever */
1138                   v_string = g_strerror (errno);
1139                   v_uint = v_string ? strlen (v_string) : 0;
1140                   conv_len += MAX (256, v_uint);
1141                   break;
1142
1143                   /* handle invalid cases
1144                    */
1145                 case '\000':
1146                   /* no conversion specification, bad bad */
1147                   conv_len += format - spec_start;
1148                   break;
1149                 default:
1150                   if (may_warn)
1151                     g_warning (G_GNUC_PRETTY_FUNCTION
1152                                "(): unable to handle `%c' while parsing format",
1153                                c);
1154                   break;
1155                 }
1156               conv_done |= conv_len > 0;
1157             }
1158           while (!conv_done);
1159           /* handle width specifications */
1160           conv_len = MAX (conv_len, MAX (spec.precision, spec.min_width));
1161           /* handle flags */
1162           conv_len += spec.alternate_format ? 2 : 0;
1163           conv_len += (spec.add_space || spec.add_sign || spec.possible_sign);
1164           /* finally done */
1165           len += conv_len;
1166         } /* else (c == '%') */
1167     } /* while (*format) */
1168
1169   return len;
1170 }
1171
1172 gsize
1173 g_printf_string_upper_bound (const gchar *format,
1174                              va_list      args)
1175 {
1176   return printf_string_upper_bound (format, TRUE, args);
1177 }
1178
1179 void
1180 g_messages_init (void)
1181 {
1182   g_messages_lock = g_mutex_new();
1183   g_log_depth = g_private_new(NULL);
1184 }