Change LGPL-2.1+ to LGPL-2.1-or-later
[platform/upstream/glib.git] / glib / glib-init.c
1 /*
2  * Copyright © 2011 Canonical Limited
3  *
4  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  *
19  * Author: Ryan Lortie <desrt@desrt.ca>
20  */
21
22 #include "config.h"
23
24 #include "glib-init.h"
25 #include "gmacros.h"
26 #include "gtypes.h"
27 #include "gutils.h"     /* for GDebugKey */
28 #include "gconstructor.h"
29 #include "gmem.h"       /* for g_mem_gc_friendly */
30
31 #include <string.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <ctype.h>
35
36 /* Deliberately not checking HAVE_STDINT_H here: we officially require a
37  * C99 toolchain, which implies <stdint.h>, int8_t and so on. If your
38  * toolchain does not have this, now would be a good time to upgrade. */
39 #include <stdint.h>
40
41 /* This seems as good a place as any to make static assertions about platform
42  * assumptions we make throughout GLib. */
43
44 /* We do not support 36-bit bytes or other historical curiosities. */
45 G_STATIC_ASSERT (CHAR_BIT == 8);
46
47 /* We assume that data pointers are the same size as function pointers... */
48 G_STATIC_ASSERT (sizeof (gpointer) == sizeof (GFunc));
49 G_STATIC_ASSERT (G_ALIGNOF (gpointer) == G_ALIGNOF (GFunc));
50 /* ... and that all function pointers are the same size. */
51 G_STATIC_ASSERT (sizeof (GFunc) == sizeof (GCompareDataFunc));
52 G_STATIC_ASSERT (G_ALIGNOF (GFunc) == G_ALIGNOF (GCompareDataFunc));
53
54 /* We assume that "small" enums (those where all values fit in INT32_MIN
55  * to INT32_MAX) are exactly int-sized. In particular, we assume that if
56  * an enum has no members that exceed the range of char/short, the
57  * compiler will make it int-sized anyway, so adding a member later that
58  * *does* exceed the range of char/short is not an ABI break. */
59 typedef enum {
60     TEST_CHAR_0 = 0
61 } TestChar;
62 typedef enum {
63     TEST_SHORT_0 = 0,
64     TEST_SHORT_256 = 256
65 } TestShort;
66 typedef enum {
67     TEST_INT32_MIN = G_MININT32,
68     TEST_INT32_MAX = G_MAXINT32
69 } TestInt;
70 G_STATIC_ASSERT (sizeof (TestChar) == sizeof (int));
71 G_STATIC_ASSERT (sizeof (TestShort) == sizeof (int));
72 G_STATIC_ASSERT (sizeof (TestInt) == sizeof (int));
73 G_STATIC_ASSERT (G_ALIGNOF (TestChar) == G_ALIGNOF (int));
74 G_STATIC_ASSERT (G_ALIGNOF (TestShort) == G_ALIGNOF (int));
75 G_STATIC_ASSERT (G_ALIGNOF (TestInt) == G_ALIGNOF (int));
76
77 G_STATIC_ASSERT (sizeof (gchar) == 1);
78 G_STATIC_ASSERT (sizeof (guchar) == 1);
79 G_STATIC_ASSERT (sizeof (gint8) * CHAR_BIT == 8);
80 G_STATIC_ASSERT (sizeof (guint8) * CHAR_BIT == 8);
81 G_STATIC_ASSERT (sizeof (gint16) * CHAR_BIT == 16);
82 G_STATIC_ASSERT (sizeof (guint16) * CHAR_BIT == 16);
83 G_STATIC_ASSERT (sizeof (gint32) * CHAR_BIT == 32);
84 G_STATIC_ASSERT (sizeof (guint32) * CHAR_BIT == 32);
85 G_STATIC_ASSERT (sizeof (gint64) * CHAR_BIT == 64);
86 G_STATIC_ASSERT (sizeof (guint64) * CHAR_BIT == 64);
87
88 G_STATIC_ASSERT (sizeof (void *) == GLIB_SIZEOF_VOID_P);
89 G_STATIC_ASSERT (sizeof (gintptr) == sizeof (void *));
90 G_STATIC_ASSERT (sizeof (guintptr) == sizeof (void *));
91
92 G_STATIC_ASSERT (sizeof (short) == sizeof (gshort));
93 G_STATIC_ASSERT (G_MINSHORT == SHRT_MIN);
94 G_STATIC_ASSERT (G_MAXSHORT == SHRT_MAX);
95 G_STATIC_ASSERT (sizeof (unsigned short) == sizeof (gushort));
96 G_STATIC_ASSERT (G_MAXUSHORT == USHRT_MAX);
97
98 G_STATIC_ASSERT (sizeof (int) == sizeof (gint));
99 G_STATIC_ASSERT (G_MININT == INT_MIN);
100 G_STATIC_ASSERT (G_MAXINT == INT_MAX);
101 G_STATIC_ASSERT (sizeof (unsigned int) == sizeof (guint));
102 G_STATIC_ASSERT (G_MAXUINT == UINT_MAX);
103
104 G_STATIC_ASSERT (sizeof (long) == GLIB_SIZEOF_LONG);
105 G_STATIC_ASSERT (sizeof (long) == sizeof (glong));
106 G_STATIC_ASSERT (G_MINLONG == LONG_MIN);
107 G_STATIC_ASSERT (G_MAXLONG == LONG_MAX);
108 G_STATIC_ASSERT (sizeof (unsigned long) == sizeof (gulong));
109 G_STATIC_ASSERT (G_MAXULONG == ULONG_MAX);
110
111 G_STATIC_ASSERT (G_HAVE_GINT64 == 1);
112
113 G_STATIC_ASSERT (sizeof (size_t) == GLIB_SIZEOF_SIZE_T);
114 /* Not a typo: ssize_t is POSIX, not Standard C, but if it exists then
115  * it's the same size as size_t. */
116 G_STATIC_ASSERT (sizeof (size_t) == GLIB_SIZEOF_SSIZE_T);
117 G_STATIC_ASSERT (sizeof (gsize) == GLIB_SIZEOF_SSIZE_T);
118 G_STATIC_ASSERT (sizeof (gsize) == sizeof (size_t));
119 G_STATIC_ASSERT (G_MAXSIZE == SIZE_MAX);
120 /* Again this is size_t not ssize_t, because ssize_t is POSIX, not C99 */
121 G_STATIC_ASSERT (sizeof (gssize) == sizeof (size_t));
122 G_STATIC_ASSERT (G_ALIGNOF (gsize) == G_ALIGNOF (size_t));
123 G_STATIC_ASSERT (G_ALIGNOF (gssize) == G_ALIGNOF (size_t));
124 /* We assume that GSIZE_TO_POINTER is reversible by GPOINTER_TO_SIZE
125  * without losing information.
126  * However, we do not assume that GPOINTER_TO_SIZE can store an arbitrary
127  * pointer in a gsize (known to be false on CHERI). */
128 G_STATIC_ASSERT (sizeof (size_t) <= sizeof (void *));
129 /* Standard C does not guarantee that size_t is the same as uintptr_t,
130  * but GLib currently assumes they are the same: see
131  * <https://gitlab.gnome.org/GNOME/glib/-/issues/2842>.
132  *
133  * To enable working on bringup for new architectures these assertions
134  * can be disabled with -DG_ENABLE_EXPERIMENTAL_ABI_COMPILATION.
135  *
136  * FIXME: remove these assertions once the API/ABI has stabilized. */
137 #ifndef G_ENABLE_EXPERIMENTAL_ABI_COMPILATION
138 G_STATIC_ASSERT (sizeof (size_t) == sizeof (uintptr_t));
139 G_STATIC_ASSERT (G_ALIGNOF (size_t) == G_ALIGNOF (uintptr_t));
140 #endif
141 /* goffset is always 64-bit, even if off_t is only 32-bit
142  * (compiling without large-file-support on 32-bit) */
143 G_STATIC_ASSERT (sizeof (goffset) == sizeof (gint64));
144 G_STATIC_ASSERT (G_ALIGNOF (goffset) == G_ALIGNOF (gint64));
145
146 G_STATIC_ASSERT (sizeof (gfloat) == sizeof (float));
147 G_STATIC_ASSERT (G_ALIGNOF (gfloat) == G_ALIGNOF (float));
148 G_STATIC_ASSERT (sizeof (gdouble) == sizeof (double));
149 G_STATIC_ASSERT (G_ALIGNOF (gdouble) == G_ALIGNOF (double));
150
151 G_STATIC_ASSERT (sizeof (gintptr) == sizeof (intptr_t));
152 G_STATIC_ASSERT (sizeof (guintptr) == sizeof (uintptr_t));
153 G_STATIC_ASSERT (G_ALIGNOF (gintptr) == G_ALIGNOF (intptr_t));
154 G_STATIC_ASSERT (G_ALIGNOF (guintptr) == G_ALIGNOF (uintptr_t));
155
156 G_STATIC_ASSERT (sizeof (gint8) == sizeof (int8_t));
157 G_STATIC_ASSERT (sizeof (guint8) == sizeof (uint8_t));
158 G_STATIC_ASSERT (G_ALIGNOF (gint8) == G_ALIGNOF (int8_t));
159 G_STATIC_ASSERT (G_ALIGNOF (guint8) == G_ALIGNOF (uint8_t));
160
161 G_STATIC_ASSERT (sizeof (gint16) == sizeof (int16_t));
162 G_STATIC_ASSERT (sizeof (guint16) == sizeof (uint16_t));
163 G_STATIC_ASSERT (G_ALIGNOF (gint16) == G_ALIGNOF (int16_t));
164 G_STATIC_ASSERT (G_ALIGNOF (guint16) == G_ALIGNOF (uint16_t));
165
166 G_STATIC_ASSERT (sizeof (gint32) == sizeof (int32_t));
167 G_STATIC_ASSERT (sizeof (guint32) == sizeof (uint32_t));
168 G_STATIC_ASSERT (G_ALIGNOF (gint32) == G_ALIGNOF (int32_t));
169 G_STATIC_ASSERT (G_ALIGNOF (guint32) == G_ALIGNOF (uint32_t));
170
171 G_STATIC_ASSERT (sizeof (gint64) == sizeof (int64_t));
172 G_STATIC_ASSERT (sizeof (guint64) == sizeof (uint64_t));
173 G_STATIC_ASSERT (G_ALIGNOF (gint64) == G_ALIGNOF (int64_t));
174 G_STATIC_ASSERT (G_ALIGNOF (guint64) == G_ALIGNOF (uint64_t));
175
176 /**
177  * g_mem_gc_friendly:
178  *
179  * This variable is %TRUE if the `G_DEBUG` environment variable
180  * includes the key `gc-friendly`.
181  */
182 gboolean g_mem_gc_friendly = FALSE;
183
184 GLogLevelFlags g_log_msg_prefix = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_WARNING |
185                                   G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_DEBUG;
186 GLogLevelFlags g_log_always_fatal = G_LOG_FATAL_MASK;
187
188 static gboolean
189 debug_key_matches (const gchar *key,
190                    const gchar *token,
191                    guint        length)
192 {
193   /* may not call GLib functions: see note in g_parse_debug_string() */
194   for (; length; length--, key++, token++)
195     {
196       char k = (*key   == '_') ? '-' : tolower (*key  );
197       char t = (*token == '_') ? '-' : tolower (*token);
198
199       if (k != t)
200         return FALSE;
201     }
202
203   return *key == '\0';
204 }
205
206 /* The GVariant documentation indirectly says that int is at least 32 bits
207  * (by saying that b, y, n, q, i, u, h are promoted to int). On any
208  * reasonable platform, int is in fact *exactly* 32 bits long, because
209  * otherwise, {signed char, short, int} wouldn't be sufficient to provide
210  * {int8_t, int16_t, int32_t}. */
211 G_STATIC_ASSERT (sizeof (int) == sizeof (gint32));
212
213 /**
214  * g_parse_debug_string:
215  * @string: (nullable): a list of debug options separated by colons, spaces, or
216  * commas, or %NULL.
217  * @keys: (array length=nkeys): pointer to an array of #GDebugKey which associate
218  *     strings with bit flags.
219  * @nkeys: the number of #GDebugKeys in the array.
220  *
221  * Parses a string containing debugging options
222  * into a %guint containing bit flags. This is used
223  * within GDK and GTK to parse the debug options passed on the
224  * command line or through environment variables.
225  *
226  * If @string is equal to "all", all flags are set. Any flags
227  * specified along with "all" in @string are inverted; thus,
228  * "all,foo,bar" or "foo,bar,all" sets all flags except those
229  * corresponding to "foo" and "bar".
230  *
231  * If @string is equal to "help", all the available keys in @keys
232  * are printed out to standard error.
233  *
234  * Returns: the combined set of bit flags.
235  */
236 guint
237 g_parse_debug_string  (const gchar     *string,
238                        const GDebugKey *keys,
239                        guint            nkeys)
240 {
241   guint i;
242   guint result = 0;
243
244   if (string == NULL)
245     return 0;
246
247   /* this function is used during the initialisation of gmessages, gmem
248    * and gslice, so it may not do anything that causes memory to be
249    * allocated or risks messages being emitted.
250    *
251    * this means, more or less, that this code may not call anything
252    * inside GLib.
253    */
254
255   if (!strcasecmp (string, "help"))
256     {
257       /* using stdio directly for the reason stated above */
258       fprintf (stderr, "Supported debug values:");
259       for (i = 0; i < nkeys; i++)
260         fprintf (stderr, " %s", keys[i].key);
261       fprintf (stderr, " all help\n");
262     }
263   else
264     {
265       const gchar *p = string;
266       const gchar *q;
267       gboolean invert = FALSE;
268
269       while (*p)
270        {
271          q = strpbrk (p, ":;, \t");
272          if (!q)
273            q = p + strlen (p);
274
275          if (debug_key_matches ("all", p, q - p))
276            {
277              invert = TRUE;
278            }
279          else
280            {
281              for (i = 0; i < nkeys; i++)
282                if (debug_key_matches (keys[i].key, p, q - p))
283                  result |= keys[i].value;
284            }
285
286          p = q;
287          if (*p)
288            p++;
289        }
290
291       if (invert)
292         {
293           guint all_flags = 0;
294
295           for (i = 0; i < nkeys; i++)
296             all_flags |= keys[i].value;
297
298           result = all_flags & (~result);
299         }
300     }
301
302   return result;
303 }
304
305 static guint
306 g_parse_debug_envvar (const gchar     *envvar,
307                       const GDebugKey *keys,
308                       gint             n_keys,
309                       guint            default_value)
310 {
311   const gchar *value;
312
313 #ifdef OS_WIN32
314   /* "fatal-warnings,fatal-criticals,all,help" is pretty short */
315   gchar buffer[100];
316
317   if (GetEnvironmentVariable (envvar, buffer, 100) < 100)
318     value = buffer;
319   else
320     return 0;
321 #else
322   value = getenv (envvar);
323 #endif
324
325   if (value == NULL)
326     return default_value;
327
328   return g_parse_debug_string (value, keys, n_keys);
329 }
330
331 static void
332 g_messages_prefixed_init (void)
333 {
334   const GDebugKey keys[] = {
335     { "error", G_LOG_LEVEL_ERROR },
336     { "critical", G_LOG_LEVEL_CRITICAL },
337     { "warning", G_LOG_LEVEL_WARNING },
338     { "message", G_LOG_LEVEL_MESSAGE },
339     { "info", G_LOG_LEVEL_INFO },
340     { "debug", G_LOG_LEVEL_DEBUG }
341   };
342
343   g_log_msg_prefix = g_parse_debug_envvar ("G_MESSAGES_PREFIXED", keys, G_N_ELEMENTS (keys), g_log_msg_prefix);
344 }
345
346 static void
347 g_debug_init (void)
348 {
349   const GDebugKey keys[] = {
350     { "gc-friendly", 1 },
351     {"fatal-warnings",  G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL },
352     {"fatal-criticals", G_LOG_LEVEL_CRITICAL }
353   };
354   GLogLevelFlags flags;
355
356   flags = g_parse_debug_envvar ("G_DEBUG", keys, G_N_ELEMENTS (keys), 0);
357
358   g_log_always_fatal |= flags & G_LOG_LEVEL_MASK;
359
360   g_mem_gc_friendly = flags & 1;
361 }
362
363 void
364 glib_init (void)
365 {
366   static gboolean glib_inited;
367
368   if (glib_inited)
369     return;
370
371   glib_inited = TRUE;
372
373   g_messages_prefixed_init ();
374   g_debug_init ();
375   g_quark_init ();
376   g_error_init ();
377 }
378
379 #ifdef G_PLATFORM_WIN32
380
381 HMODULE glib_dll = NULL;
382 void glib_win32_init (void);
383
384 void
385 glib_win32_init (void)
386 {
387   /* May be called more than once in static compilation mode */
388   static gboolean win32_already_init = FALSE;
389   if (!win32_already_init)
390     {
391       win32_already_init = TRUE;
392
393       g_crash_handler_win32_init ();
394 #ifdef THREADS_WIN32
395       g_thread_win32_init ();
396 #endif
397
398       g_clock_win32_init ();
399       glib_init ();
400       /* must go after glib_init */
401       g_console_win32_init ();
402     }
403 }
404
405 static void
406 glib_win32_deinit (gboolean detach_thread)
407 {
408 #ifdef THREADS_WIN32
409   if (detach_thread)
410     g_thread_win32_process_detach ();
411 #endif
412   g_crash_handler_win32_deinit ();
413 }
414
415 #ifndef GLIB_STATIC_COMPILATION
416
417 BOOL WINAPI DllMain (HINSTANCE hinstDLL,
418                      DWORD     fdwReason,
419                      LPVOID    lpvReserved);
420
421 BOOL WINAPI
422 DllMain (HINSTANCE hinstDLL,
423          DWORD     fdwReason,
424          LPVOID    lpvReserved)
425 {
426   switch (fdwReason)
427     {
428     case DLL_PROCESS_ATTACH:
429       glib_dll = hinstDLL;
430       glib_win32_init ();
431       break;
432
433     case DLL_THREAD_DETACH:
434 #ifdef THREADS_WIN32
435       g_thread_win32_thread_detach ();
436 #endif
437       break;
438
439     case DLL_PROCESS_DETACH:
440       glib_win32_deinit (lpvReserved == NULL);
441       break;
442
443     default:
444       /* do nothing */
445       ;
446     }
447
448   return TRUE;
449 }
450
451 #elif defined(G_HAS_CONSTRUCTORS) /* && G_PLATFORM_WIN32 && GLIB_STATIC_COMPILATION */
452 #ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA
453 #pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(glib_init_ctor)
454 #endif
455 #ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA
456 #pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(glib_init_dtor)
457 #endif
458
459 G_DEFINE_CONSTRUCTOR (glib_init_ctor)
460
461 static void
462 glib_init_ctor (void)
463 {
464   glib_win32_init ();
465 }
466
467 G_DEFINE_DESTRUCTOR (glib_init_dtor)
468
469 static void
470 glib_init_dtor (void)
471 {
472   glib_win32_deinit (FALSE);
473 }
474
475 #else /* G_PLATFORM_WIN32 && GLIB_STATIC_COMPILATION && !G_HAS_CONSTRUCTORS */
476 #error Your platform/compiler is missing constructor support
477 #endif /* GLIB_STATIC_COMPILATION */
478
479 #elif defined(G_HAS_CONSTRUCTORS) /* && !G_PLATFORM_WIN32 */
480
481 #ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA
482 #pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(glib_init_ctor)
483 #endif
484 G_DEFINE_CONSTRUCTOR(glib_init_ctor)
485
486 static void
487 glib_init_ctor (void)
488 {
489   glib_init ();
490 }
491
492 #else /* !G_PLATFORM_WIN32 && !G_HAS_CONSTRUCTORS */
493 # error Your platform/compiler is missing constructor support
494 #endif /* G_PLATFORM_WIN32 */