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