Use the #if branch with G_BREAKPOINT() also on Win32. Remove the separate
[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 #ifndef HAVE_C99_VSNPRINTF
75 static gsize printf_string_upper_bound (const gchar *format,
76                                         gboolean     may_warn,
77                                         va_list      args);
78 #endif /* !HAVE_C99_VSNPRINTF */
79
80
81 /* --- variables --- */
82
83 static GMutex* g_messages_lock = NULL;
84
85 static GLogDomain    *g_log_domains = NULL;
86 static GLogLevelFlags g_log_always_fatal = G_LOG_FATAL_MASK;
87 static GPrintFunc     glib_print_func = NULL;
88 static GPrintFunc     glib_printerr_func = NULL;
89
90 static GPrivate* g_log_depth = NULL;
91
92 /* --- functions --- */
93 #ifdef G_OS_WIN32
94 #  define STRICT
95 #  include <windows.h>
96 #  undef STRICT
97 #  include <process.h>          /* For _getpid() */
98
99 static gboolean alloc_console_called = FALSE;
100
101 static gboolean gonna_abort = FALSE;
102
103 /* This default message will usually be overwritten. */
104 /* Yes, a fixed size buffer is bad. So sue me. But g_error is never
105  * with huge strings, is it? */
106 static char fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
107 static char *fatal_msg_ptr = fatal_msg_buf;
108
109 /* Just use stdio. If we're out of memory, we're hosed anyway. */
110 #undef write
111 static inline int
112 dowrite (GFileDescriptor fd,
113          const void  *buf,
114          unsigned int len)
115 {
116   if (gonna_abort)
117     {
118       memcpy (fatal_msg_ptr, buf, len);
119       fatal_msg_ptr += len;
120       *fatal_msg_ptr = 0;
121       return len;
122     }
123
124   fwrite (buf, len, 1, fd);
125   fflush (fd);
126
127   return len;
128 }
129
130 #define write(fd, buf, len) dowrite(fd, buf, len)
131
132 static void
133 ensure_stdout_valid (void)
134 {
135   HANDLE handle;
136
137   if (gonna_abort)
138     return;
139
140   if (!alloc_console_called)
141     {
142       handle = GetStdHandle (STD_OUTPUT_HANDLE);
143   
144       if (handle == INVALID_HANDLE_VALUE)
145         {
146           AllocConsole ();
147           alloc_console_called = TRUE;
148           freopen ("CONOUT$", "w", stdout);
149         }
150     }
151 }
152 #else
153 #define ensure_stdout_valid()   /* Define as empty */
154 #endif
155
156 static void
157 write_unsigned (GFileDescriptor fd,
158                 gulong          num,
159                 guint           radix)
160 {
161   char buffer[64];
162   gulong tmp;
163   char c;
164   int i, n;
165
166   g_return_if_fail (radix >= 2 && radix <= 36);
167   
168   if (!num)
169     {
170       write (fd, "0", 1);
171       return;
172     } 
173   
174   if (radix == 16)
175     write (fd, "0x", 2);
176   else if (radix == 8)
177     write (fd, "0", 1);
178         
179   n = 0;
180   tmp = num;
181   while (tmp)
182     {
183       tmp /= radix;
184       n++;
185     }
186
187   i = n;
188   while (num)
189     {
190       i--;
191       c = (num % radix);
192       if (c < 10)
193         buffer[i] = c + '0';
194       else
195         buffer[i] = c + 'a' - 10;
196       num /= radix;
197     }
198   
199   write (fd, buffer, n);
200 }
201
202 static void
203 write_string (GFileDescriptor fd,
204               gchar *string)
205 {
206   write (fd, string, strlen (string));
207 }
208
209 static void
210 g_log_write_prefix (GFileDescriptor fd,
211                     GLogLevelFlags mask)
212 {
213   static GLogLevelFlags g_log_msg_prefix = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_DEBUG;
214   static gboolean initialized = FALSE;
215   
216   g_mutex_lock (g_messages_lock);
217
218   if (!initialized)
219     {
220       const gchar *val;
221       initialized = TRUE;
222
223       val = g_getenv ("G_MESSAGES_PREFIXED");
224       
225       if (val)
226         {
227           static const GDebugKey keys[] = {
228             { "error", G_LOG_LEVEL_ERROR },
229             { "critical", G_LOG_LEVEL_CRITICAL },
230             { "warning", G_LOG_LEVEL_WARNING },
231             { "message", G_LOG_LEVEL_MESSAGE },
232             { "info", G_LOG_LEVEL_INFO },
233             { "debug", G_LOG_LEVEL_DEBUG }
234           };
235           
236           g_log_msg_prefix = g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
237         }
238     }
239   
240   g_mutex_unlock (g_messages_lock);
241   
242   if ((g_log_msg_prefix & mask) == mask)
243     {
244       gchar *prg_name;
245
246       prg_name = g_get_prgname ();
247
248       if (!prg_name)
249         write_string (fd, "(process:");
250       else
251         {
252           write_string (fd, prg_name);
253           write_string (fd, " (pid:");
254         }
255
256       write_unsigned (fd, getpid (), 10);
257       write_string (fd, "): ");
258     }
259 }
260
261 static inline GLogDomain*
262 g_log_find_domain (const gchar *log_domain)
263 {
264   register GLogDomain *domain;
265   
266   g_mutex_lock (g_messages_lock);
267   domain = g_log_domains;
268   while (domain)
269     {
270       if (strcmp (domain->log_domain, log_domain) == 0)
271         {
272           g_mutex_unlock (g_messages_lock);
273           return domain;
274         }
275       domain = domain->next;
276     }
277   g_mutex_unlock (g_messages_lock);
278   return NULL;
279 }
280
281 static inline GLogDomain*
282 g_log_domain_new (const gchar *log_domain)
283 {
284   register GLogDomain *domain;
285
286   domain = g_new (GLogDomain, 1);
287   domain->log_domain = g_strdup (log_domain);
288   domain->fatal_mask = G_LOG_FATAL_MASK;
289   domain->handlers = NULL;
290   
291   g_mutex_lock (g_messages_lock);
292   domain->next = g_log_domains;
293   g_log_domains = domain;
294   g_mutex_unlock (g_messages_lock);
295   
296   return domain;
297 }
298
299 static inline void
300 g_log_domain_check_free (GLogDomain *domain)
301 {
302   if (domain->fatal_mask == G_LOG_FATAL_MASK &&
303       domain->handlers == NULL)
304     {
305       register GLogDomain *last, *work;
306       
307       last = NULL;  
308
309       g_mutex_lock (g_messages_lock);
310       work = g_log_domains;
311       while (work)
312         {
313           if (work == domain)
314             {
315               if (last)
316                 last->next = domain->next;
317               else
318                 g_log_domains = domain->next;
319               g_free (domain->log_domain);
320               g_free (domain);
321               break;
322             }
323           last = work;
324           work = last->next;
325         }  
326       g_mutex_unlock (g_messages_lock);
327     }
328 }
329
330 static inline GLogFunc
331 g_log_domain_get_handler (GLogDomain    *domain,
332                           GLogLevelFlags log_level,
333                           gpointer      *data)
334 {
335   if (domain && log_level)
336     {
337       register GLogHandler *handler;
338       
339       handler = domain->handlers;
340       while (handler)
341         {
342           if ((handler->log_level & log_level) == log_level)
343             {
344               *data = handler->data;
345               return handler->log_func;
346             }
347           handler = handler->next;
348         }
349     }
350   return g_log_default_handler;
351 }
352
353 GLogLevelFlags
354 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
355 {
356   GLogLevelFlags old_mask;
357
358   /* restrict the global mask to levels that are known to glib */
359   fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
360   /* force errors to be fatal */
361   fatal_mask |= G_LOG_LEVEL_ERROR;
362   /* remove bogus flag */
363   fatal_mask &= ~G_LOG_FLAG_FATAL;
364
365   g_mutex_lock (g_messages_lock);
366   old_mask = g_log_always_fatal;
367   g_log_always_fatal = fatal_mask;
368   g_mutex_unlock (g_messages_lock);
369
370   return old_mask;
371 }
372
373 GLogLevelFlags
374 g_log_set_fatal_mask (const gchar    *log_domain,
375                       GLogLevelFlags  fatal_mask)
376 {
377   GLogLevelFlags old_flags;
378   register GLogDomain *domain;
379   
380   if (!log_domain)
381     log_domain = "";
382   
383   /* force errors to be fatal */
384   fatal_mask |= G_LOG_LEVEL_ERROR;
385   /* remove bogus flag */
386   fatal_mask &= ~G_LOG_FLAG_FATAL;
387   
388   domain = g_log_find_domain (log_domain);
389   if (!domain)
390     domain = g_log_domain_new (log_domain);
391   old_flags = domain->fatal_mask;
392   
393   domain->fatal_mask = fatal_mask;
394   g_log_domain_check_free (domain);
395   
396   return old_flags;
397 }
398
399 guint
400 g_log_set_handler (const gchar    *log_domain,
401                    GLogLevelFlags  log_levels,
402                    GLogFunc        log_func,
403                    gpointer        user_data)
404 {
405   register GLogDomain *domain;
406   register GLogHandler *handler;
407   static guint handler_id = 0;
408   
409   g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
410   g_return_val_if_fail (log_func != NULL, 0);
411   
412   if (!log_domain)
413     log_domain = "";
414   
415   domain = g_log_find_domain (log_domain);
416   if (!domain)
417     domain = g_log_domain_new (log_domain);
418   
419   handler = g_new (GLogHandler, 1);
420   g_mutex_lock (g_messages_lock);
421   handler->id = ++handler_id;
422   g_mutex_unlock (g_messages_lock);
423   handler->log_level = log_levels;
424   handler->log_func = log_func;
425   handler->data = user_data;
426   handler->next = domain->handlers;
427   domain->handlers = handler;
428   
429   return handler_id;
430 }
431
432 void
433 g_log_remove_handler (const gchar *log_domain,
434                       guint        handler_id)
435 {
436   register GLogDomain *domain;
437   
438   g_return_if_fail (handler_id > 0);
439   
440   if (!log_domain)
441     log_domain = "";
442   
443   domain = g_log_find_domain (log_domain);
444   if (domain)
445     {
446       register GLogHandler *work, *last;
447       
448       last = NULL;
449       work = domain->handlers;
450       while (work)
451         {
452           if (work->id == handler_id)
453             {
454               if (last)
455                 last->next = work->next;
456               else
457                 domain->handlers = work->next;
458               g_free (work);
459               g_log_domain_check_free (domain);
460               return;
461             }
462           last = work;
463           work = last->next;
464         }
465     }
466   g_warning ("g_log_remove_handler(): could not find handler with id `%d' for domain \"%s\"",
467              handler_id,
468              log_domain);
469 }
470
471 void
472 g_logv (const gchar   *log_domain,
473         GLogLevelFlags log_level,
474         const gchar   *format,
475         va_list        args1)
476 {
477   gchar buffer[1025];
478   register gint i;
479
480 #ifndef  HAVE_VSNPRINTF
481   va_list args2;
482 #endif  /* HAVE_VSNPRINTF */
483   
484   log_level &= G_LOG_LEVEL_MASK;
485   if (!log_level)
486     return;
487   
488   /* we use a stack buffer of fixed size, because we might get called
489    * recursively.
490    */
491 #ifdef  HAVE_VSNPRINTF
492   vsnprintf (buffer, 1024, format, args1);
493 #else   /* !HAVE_VSNPRINTF */
494   G_VA_COPY (args2, args1);
495   if (printf_string_upper_bound (format, FALSE, args1) < 1024)
496     vsprintf (buffer, format, args2);
497   else
498     {
499       /* since we might be out of memory, we can't use g_vsnprintf(). */
500       /* we are out of luck here */
501       strncpy (buffer, format, 1024);
502       buffer[1024] = 0;
503     }
504   va_end (args2);
505 #endif  /* !HAVE_VSNPRINTF */
506   
507   for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
508     {
509       register GLogLevelFlags test_level;
510       
511       test_level = 1 << i;
512       if (log_level & test_level)
513         {
514           guint depth = GPOINTER_TO_UINT (g_private_get (g_log_depth));
515           GLogDomain *domain;
516           GLogFunc log_func;
517           gpointer data = NULL;
518           
519           domain = g_log_find_domain (log_domain ? log_domain : "");
520           
521           if (depth)
522             test_level |= G_LOG_FLAG_RECURSION;
523           
524           depth++;
525           g_private_set (g_log_depth, GUINT_TO_POINTER (depth));
526
527           g_mutex_lock (g_messages_lock);
528           if ((((domain ? domain->fatal_mask : G_LOG_FATAL_MASK) | 
529                 g_log_always_fatal) & test_level) != 0)
530             test_level |= G_LOG_FLAG_FATAL;  
531           g_mutex_unlock (g_messages_lock);
532
533           log_func = g_log_domain_get_handler (domain, test_level, &data);
534           log_func (log_domain, test_level, buffer, data);
535           
536           /* *domain can be cluttered now */
537           
538           if (test_level & G_LOG_FLAG_FATAL)
539             {
540 #ifdef G_OS_WIN32
541               MessageBox (NULL, fatal_msg_buf, NULL, MB_OK);
542 #endif
543 #if defined (G_ENABLE_DEBUG) && (defined (SIGTRAP) || defined (G_OS_WIN32))
544               if (!(test_level & G_LOG_FLAG_RECURSION))
545                 G_BREAKPOINT ();
546               else
547                 abort ();
548 #else /* !G_ENABLE_DEBUG || !(SIGTRAP || G_OS_WIN32) */
549               abort ();
550 #endif /* !G_ENABLE_DEBUG || !(SIGTRAP || G_OS_WIN32) */
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 #ifndef HAVE_C99_VSNPRINTF
862
863 typedef struct
864 {
865   guint min_width;
866   guint precision;
867   gboolean alternate_format, zero_padding, adjust_left, locale_grouping;
868   gboolean add_space, add_sign, possible_sign, seen_precision;
869   gboolean mod_half, mod_long, mod_extra_long;
870 } PrintfArgSpec;
871
872 static gsize
873 printf_string_upper_bound (const gchar *format,
874                            gboolean     may_warn,
875                            va_list      args)
876 {
877   static const gboolean honour_longs = SIZEOF_LONG > 4 || SIZEOF_VOID_P > 4;
878   gsize len = 1;
879
880   if (!format)
881     return len;
882
883   while (*format)
884     {
885       register gchar c = *format++;
886
887       if (c != '%')
888         len += 1;
889       else /* (c == '%') */
890         {
891           PrintfArgSpec spec = { 0, };
892           gboolean seen_l = FALSE, conv_done = FALSE;
893           gsize conv_len = 0;
894           const gchar *spec_start = format;
895
896           do
897             {
898               c = *format++;
899               switch (c)
900                 {
901                   GDoubleIEEE754 u_double;
902                   guint v_uint;
903                   gint v_int;
904                   const gchar *v_string;
905
906                   /* beware of positional parameters
907                    */
908                 case '$':
909                   if (may_warn)
910                     g_warning (G_GNUC_PRETTY_FUNCTION
911                                "(): unable to handle positional parameters (%%n$)");
912                   len += 1024; /* try adding some safety padding */
913                   conv_done = TRUE;
914                   break;
915
916                   /* parse flags
917                    */
918                 case '#':
919                   spec.alternate_format = TRUE;
920                   break;
921                 case '0':
922                   spec.zero_padding = TRUE;
923                   break;
924                 case '-':
925                   spec.adjust_left = TRUE;
926                   break;
927                 case ' ':
928                   spec.add_space = TRUE;
929                   break;
930                 case '+':
931                   spec.add_sign = TRUE;
932                   break;
933                 case '\'':
934                   spec.locale_grouping = TRUE;
935                   break;
936
937                   /* parse output size specifications
938                    */
939                 case '.':
940                   spec.seen_precision = TRUE;
941                   break;
942                 case '1':
943                 case '2':
944                 case '3':
945                 case '4':
946                 case '5':
947                 case '6':
948                 case '7':
949                 case '8':
950                 case '9':
951                   v_uint = c - '0';
952                   c = *format;
953                   while (c >= '0' && c <= '9')
954                     {
955                       format++;
956                       v_uint = v_uint * 10 + c - '0';
957                       c = *format;
958                     }
959                   if (spec.seen_precision)
960                     spec.precision = MAX (spec.precision, v_uint);
961                   else
962                     spec.min_width = MAX (spec.min_width, v_uint);
963                   break;
964                 case '*':
965                   v_int = va_arg (args, int);
966                   if (spec.seen_precision)
967                     {
968                       /* forget about negative precision */
969                       if (v_int >= 0)
970                         spec.precision = MAX (spec.precision, v_int);
971                     }
972                   else
973                     {
974                       if (v_int < 0)
975                         {
976                           v_int = - v_int;
977                           spec.adjust_left = TRUE;
978                         }
979                       spec.min_width = MAX (spec.min_width, v_int);
980                     }
981                   break;
982
983                   /* parse type modifiers
984                    */
985                 case 'h':
986                   spec.mod_half = TRUE;
987                   break;
988                 case 'l':
989                   if (!seen_l)
990                     {
991                       spec.mod_long = TRUE;
992                       seen_l = TRUE;
993                       break;
994                     }
995                   /* else, fall through */
996                 case 'L':
997                 case 'q':
998                   spec.mod_long = TRUE;
999                   spec.mod_extra_long = TRUE;
1000                   break;
1001                 case 'z':
1002                 case 'Z':
1003 #if GLIB_SIZEOF_SIZE_T > 4
1004                   spec.mod_long = TRUE;
1005                   spec.mod_extra_long = TRUE;
1006 #endif /* GLIB_SIZEOF_SIZE_T > 4 */
1007                   break;
1008                 case 't':
1009 #if GLIB_SIZEOF_PTRDIFF_T > 4
1010                   spec.mod_long = TRUE;
1011                   spec.mod_extra_long = TRUE;
1012 #endif /* GLIB_SIZEOF_PTRDIFF_T > 4 */
1013                   break;
1014                 case 'j':
1015 #if GLIB_SIZEOF_INTMAX_T > 4
1016                   spec.mod_long = TRUE;
1017                   spec.mod_extra_long = TRUE;
1018 #endif /* GLIB_SIZEOF_INTMAX_T > 4 */
1019                   break;
1020
1021                   /* parse output conversions
1022                    */
1023                 case '%':
1024                   conv_len += 1;
1025                   break;
1026                 case 'O':
1027                 case 'D':
1028                 case 'I':
1029                 case 'U':
1030                   /* some C libraries feature long variants for these as well? */
1031                   spec.mod_long = TRUE;
1032                   /* fall through */
1033                 case 'o':
1034                   conv_len += 2;
1035                   /* fall through */
1036                 case 'd':
1037                 case 'i':
1038                   conv_len += 1; /* sign */
1039                   /* fall through */
1040                 case 'u':
1041                   conv_len += 4;
1042                   /* fall through */
1043                 case 'x':
1044                 case 'X':
1045                   spec.possible_sign = TRUE;
1046                   conv_len += 10;
1047                   if (spec.mod_long && honour_longs)
1048                     conv_len *= 2;
1049                   if (spec.mod_extra_long)
1050                     conv_len *= 2;
1051                   if (spec.mod_extra_long)
1052                     {
1053                       (void) va_arg (args, gint64);
1054                     }
1055                   else if (spec.mod_long)
1056                     (void) va_arg (args, long);
1057                   else
1058                     (void) va_arg (args, int);
1059                   break;
1060                 case 'A':
1061                 case 'a':
1062                   /*          0x */
1063                   conv_len += 2;
1064                   /* fall through */
1065                 case 'g':
1066                 case 'G':
1067                 case 'e':
1068                 case 'E':
1069                 case 'f':
1070                   spec.possible_sign = TRUE;
1071                   /*          n   .   dddddddddddddddddddddddd   E   +-  eeee */
1072                   conv_len += 1 + 1 + MAX (24, spec.precision) + 1 + 1 + 4;
1073                   if (may_warn && spec.mod_extra_long)
1074                     g_warning (G_GNUC_PRETTY_FUNCTION
1075                                "(): unable to handle long double, collecting double only");
1076 #ifdef HAVE_LONG_DOUBLE
1077 #error need to implement special handling for long double
1078 #endif
1079                   u_double.v_double = va_arg (args, double);
1080                   /* %f can expand up to all significant digits before '.' (308) */
1081                   if (c == 'f' &&
1082                       u_double.mpn.biased_exponent > 0 && u_double.mpn.biased_exponent < 2047)
1083                     {
1084                       gint exp = u_double.mpn.biased_exponent;
1085
1086                       exp -= G_IEEE754_DOUBLE_BIAS;
1087                       exp = exp * G_LOG_2_BASE_10 + 1;
1088                       conv_len += ABS (exp);    /* exp can be <0 */
1089                     }
1090                   /* some printf() implementations require extra padding for rounding */
1091                   conv_len += 2;
1092                   /* we can't really handle locale specific grouping here */
1093                   if (spec.locale_grouping)
1094                     conv_len *= 2;
1095                   break;
1096                 case 'C':
1097                   spec.mod_long = TRUE;
1098                   /* fall through */
1099                 case 'c':
1100                   conv_len += spec.mod_long ? MB_LEN_MAX : 1;
1101                   (void) va_arg (args, int);
1102                   break;
1103                 case 'S':
1104                   spec.mod_long = TRUE;
1105                   /* fall through */
1106                 case 's':
1107                   v_string = va_arg (args, char*);
1108                   if (!v_string)
1109                     conv_len += 8; /* hold "(null)" */
1110                   else if (spec.seen_precision)
1111                     conv_len += spec.precision;
1112                   else
1113                     conv_len += strlen (v_string);
1114                   conv_done = TRUE;
1115                   if (spec.mod_long)
1116                     {
1117                       if (may_warn)
1118                         g_warning (G_GNUC_PRETTY_FUNCTION
1119                                    "(): unable to handle wide char strings");
1120                       len += 1024; /* try adding some safety padding */
1121                     }
1122                   break;
1123                 case 'P': /* do we actually need this? */
1124                   /* fall through */
1125                 case 'p':
1126                   spec.alternate_format = TRUE;
1127                   conv_len += 10;
1128                   if (honour_longs)
1129                     conv_len *= 2;
1130                   /* fall through */
1131                 case 'n':
1132                   conv_done = TRUE;
1133                   (void) va_arg (args, void*);
1134                   break;
1135                 case 'm':
1136                   /* there's not much we can do to be clever */
1137                   v_string = g_strerror (errno);
1138                   v_uint = v_string ? strlen (v_string) : 0;
1139                   conv_len += MAX (256, v_uint);
1140                   break;
1141
1142                   /* handle invalid cases
1143                    */
1144                 case '\000':
1145                   /* no conversion specification, bad bad */
1146                   conv_len += format - spec_start;
1147                   break;
1148                 default:
1149                   if (may_warn)
1150                     g_warning (G_GNUC_PRETTY_FUNCTION
1151                                "(): unable to handle `%c' while parsing format",
1152                                c);
1153                   break;
1154                 }
1155               conv_done |= conv_len > 0;
1156             }
1157           while (!conv_done);
1158           /* handle width specifications */
1159           conv_len = MAX (conv_len, MAX (spec.precision, spec.min_width));
1160           /* handle flags */
1161           conv_len += spec.alternate_format ? 2 : 0;
1162           conv_len += (spec.add_space || spec.add_sign || spec.possible_sign);
1163           /* finally done */
1164           len += conv_len;
1165         } /* else (c == '%') */
1166     } /* while (*format) */
1167
1168   return len;
1169 }
1170
1171 #endif /* !HAVE_C99_VSNPRINTF */
1172
1173
1174 gsize
1175 g_printf_string_upper_bound (const gchar *format,
1176                              va_list      args)
1177 {
1178 #if HAVE_C99_VSNPRINTF
1179   gchar c;
1180   return vsnprintf (&c, 1, format, args) + 1;
1181 #else
1182   return printf_string_upper_bound (format, TRUE, args);
1183 #endif
1184 }
1185
1186 void
1187 g_messages_init (void)
1188 {
1189   g_messages_lock = g_mutex_new();
1190   g_log_depth = g_private_new(NULL);
1191 }