glib-init: make static assertions about platform assumptions
[platform/upstream/glib.git] / glib / glib-init.c
1 /*
2  * Copyright © 2011 Canonical Limited
3  *
4  * This library is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * licence, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful, but
10  * 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 Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
17  * USA.
18  *
19  * Author: Ryan Lortie <desrt@desrt.ca>
20  */
21
22 #include "config.h"
23
24 #include "glib-init.h"
25
26 #include "glib-private.h"
27 #include "gtypes.h"
28 #include "gutils.h"     /* for GDebugKey */
29 #include "gconstructor.h"
30 #include "gmem.h"       /* for g_mem_gc_friendly */
31
32 #include <string.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <ctype.h>
36
37 /* This seems as good a place as any to make static assertions about platform
38  * assumptions we make throughout GLib. */
39
40 /* We assume that data pointers are the same size as function pointers... */
41 G_STATIC_ASSERT (sizeof (gpointer) == sizeof (GFunc));
42 G_STATIC_ASSERT (_g_alignof (gpointer) == _g_alignof (GFunc));
43 /* ... and that all function pointers are the same size. */
44 G_STATIC_ASSERT (sizeof (GFunc) == sizeof (GCompareDataFunc));
45 G_STATIC_ASSERT (_g_alignof (GFunc) == _g_alignof (GCompareDataFunc));
46
47 /**
48  * g_mem_gc_friendly:
49  *
50  * This variable is %TRUE if the <envar>G_DEBUG</envar> environment variable
51  * includes the key <literal>gc-friendly</literal>.
52  */
53 #ifdef ENABLE_GC_FRIENDLY_DEFAULT
54 gboolean g_mem_gc_friendly = TRUE;
55 #else
56 gboolean g_mem_gc_friendly = FALSE;
57 #endif
58 GLogLevelFlags g_log_msg_prefix = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_WARNING |
59                                   G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_DEBUG;
60 GLogLevelFlags g_log_always_fatal = G_LOG_FATAL_MASK;
61
62 static gboolean
63 debug_key_matches (const gchar *key,
64                    const gchar *token,
65                    guint        length)
66 {
67   /* may not call GLib functions: see note in g_parse_debug_string() */
68   for (; length; length--, key++, token++)
69     {
70       char k = (*key   == '_') ? '-' : tolower (*key  );
71       char t = (*token == '_') ? '-' : tolower (*token);
72
73       if (k != t)
74         return FALSE;
75     }
76
77   return *key == '\0';
78 }
79
80 /**
81  * g_parse_debug_string:
82  * @string: (allow-none): a list of debug options separated by colons, spaces, or
83  * commas, or %NULL.
84  * @keys: (array length=nkeys): pointer to an array of #GDebugKey which associate
85  *     strings with bit flags.
86  * @nkeys: the number of #GDebugKey<!-- -->s in the array.
87  *
88  * Parses a string containing debugging options
89  * into a %guint containing bit flags. This is used
90  * within GDK and GTK+ to parse the debug options passed on the
91  * command line or through environment variables.
92  *
93  * If @string is equal to <code>"all"</code>, all flags are set. Any flags
94  * specified along with <code>"all"</code> in @string are inverted; thus,
95  * <code>"all,foo,bar"</code> or <code>"foo,bar,all"</code> sets all flags
96  * except those corresponding to <code>"foo"</code> and <code>"bar"</code>.
97  *
98  * If @string is equal to <code>"help"</code>, all the available keys in @keys
99  * are printed out to standard error.
100  *
101  * Returns: the combined set of bit flags.
102  */
103 guint
104 g_parse_debug_string  (const gchar     *string,
105                        const GDebugKey *keys,
106                        guint            nkeys)
107 {
108   guint i;
109   guint result = 0;
110
111   if (string == NULL)
112     return 0;
113
114   /* this function is used during the initialisation of gmessages, gmem
115    * and gslice, so it may not do anything that causes memory to be
116    * allocated or risks messages being emitted.
117    *
118    * this means, more or less, that this code may not call anything
119    * inside GLib.
120    */
121
122   if (!strcasecmp (string, "help"))
123     {
124       /* using stdio directly for the reason stated above */
125       fprintf (stderr, "Supported debug values:");
126       for (i = 0; i < nkeys; i++)
127        fprintf (stderr, " %s", keys[i].key);
128       fprintf (stderr, " all help\n");
129     }
130   else
131     {
132       const gchar *p = string;
133       const gchar *q;
134       gboolean invert = FALSE;
135
136       while (*p)
137        {
138          q = strpbrk (p, ":;, \t");
139          if (!q)
140            q = p + strlen (p);
141
142          if (debug_key_matches ("all", p, q - p))
143            {
144              invert = TRUE;
145            }
146          else
147            {
148              for (i = 0; i < nkeys; i++)
149                if (debug_key_matches (keys[i].key, p, q - p))
150                  result |= keys[i].value;
151            }
152
153          p = q;
154          if (*p)
155            p++;
156        }
157
158       if (invert)
159         {
160           guint all_flags = 0;
161
162           for (i = 0; i < nkeys; i++)
163             all_flags |= keys[i].value;
164
165           result = all_flags & (~result);
166         }
167     }
168
169   return result;
170 }
171
172 static guint
173 g_parse_debug_envvar (const gchar     *envvar,
174                       const GDebugKey *keys,
175                       gint             n_keys,
176                       guint            default_value)
177 {
178   const gchar *value;
179
180 #ifdef OS_WIN32
181   /* "fatal-warnings,fatal-criticals,all,help" is pretty short */
182   gchar buffer[100];
183
184   if (GetEnvironmentVariable (envvar, buffer, 100) < 100)
185     value = buffer;
186   else
187     return 0;
188 #else
189   value = getenv (envvar);
190 #endif
191
192   if (value == NULL)
193     return default_value;
194
195   return g_parse_debug_string (value, keys, n_keys);
196 }
197
198 static void
199 g_messages_prefixed_init (void)
200 {
201   const GDebugKey keys[] = {
202     { "error", G_LOG_LEVEL_ERROR },
203     { "critical", G_LOG_LEVEL_CRITICAL },
204     { "warning", G_LOG_LEVEL_WARNING },
205     { "message", G_LOG_LEVEL_MESSAGE },
206     { "info", G_LOG_LEVEL_INFO },
207     { "debug", G_LOG_LEVEL_DEBUG }
208   };
209
210   g_log_msg_prefix = g_parse_debug_envvar ("G_MESSAGES_PREFIXED", keys, G_N_ELEMENTS (keys), g_log_msg_prefix);
211 }
212
213 static void
214 g_debug_init (void)
215 {
216   const GDebugKey keys[] = {
217     { "gc-friendly", 1 },
218     {"fatal-warnings",  G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL },
219     {"fatal-criticals", G_LOG_LEVEL_CRITICAL }
220   };
221   GLogLevelFlags flags;
222
223   flags = g_parse_debug_envvar ("G_DEBUG", keys, G_N_ELEMENTS (keys), 0);
224
225   g_log_always_fatal |= flags & G_LOG_LEVEL_MASK;
226
227   g_mem_gc_friendly = flags & 1;
228 }
229
230 static void
231 glib_init (void)
232 {
233   g_messages_prefixed_init ();
234   g_debug_init ();
235 }
236
237 #if defined (G_OS_WIN32)
238
239 BOOL WINAPI DllMain (HINSTANCE hinstDLL,
240                      DWORD     fdwReason,
241                      LPVOID    lpvReserved);
242
243 HMODULE glib_dll;
244
245 BOOL WINAPI
246 DllMain (HINSTANCE hinstDLL,
247          DWORD     fdwReason,
248          LPVOID    lpvReserved)
249 {
250   switch (fdwReason)
251     {
252     case DLL_PROCESS_ATTACH:
253       glib_dll = hinstDLL;
254       g_clock_win32_init ();
255 #ifdef THREADS_WIN32
256       g_thread_win32_init ();
257 #endif
258       glib_init ();
259       break;
260
261     case DLL_THREAD_DETACH:
262 #ifdef THREADS_WIN32
263       g_thread_win32_thread_detach ();
264 #endif
265       break;
266
267     default:
268       /* do nothing */
269       ;
270     }
271
272   return TRUE;
273 }
274
275 #elif defined (G_HAS_CONSTRUCTORS)
276
277 #ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA
278 #pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(glib_init_ctor)
279 #endif
280 G_DEFINE_CONSTRUCTOR(glib_init_ctor)
281
282 static void
283 glib_init_ctor (void)
284 {
285   glib_init ();
286 }
287
288 #else
289 # error Your platform/compiler is missing constructor support
290 #endif