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