Imported Upstream version 2.61.3
[platform/upstream/glib.git] / glib / gutils.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1998  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.1 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, see <http://www.gnu.org/licenses/>.
16  */
17
18 /*
19  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
20  * file for a list of people on the GLib Team.  See the ChangeLog
21  * files for a list of changes.  These files are distributed with
22  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
23  */
24
25 /* 
26  * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
27  */
28
29 #include "config.h"
30
31 #include "gutils.h"
32 #include "gutilsprivate.h"
33
34 #include <stdarg.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <locale.h>
38 #include <string.h>
39 #include <ctype.h>              /* For tolower() */
40 #include <errno.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #ifdef G_OS_UNIX
44 #include <pwd.h>
45 #include <unistd.h>
46 #endif
47 #include <sys/types.h>
48 #ifdef HAVE_SYS_PARAM_H
49 #include <sys/param.h>
50 #endif
51 #ifdef HAVE_CRT_EXTERNS_H 
52 #include <crt_externs.h> /* for _NSGetEnviron */
53 #endif
54 #ifdef HAVE_SYS_AUXV_H
55 #include <sys/auxv.h>
56 #endif
57
58 #include "glib-init.h"
59 #include "glib-private.h"
60 #include "genviron.h"
61 #include "gfileutils.h"
62 #include "ggettext.h"
63 #include "ghash.h"
64 #include "gthread.h"
65 #include "gtestutils.h"
66 #include "gunicode.h"
67 #include "gstrfuncs.h"
68 #include "garray.h"
69 #include "glibintl.h"
70 #include "gstdio.h"
71
72 #ifdef G_PLATFORM_WIN32
73 #include "gconvert.h"
74 #include "gwin32.h"
75 #endif
76
77
78 /**
79  * SECTION:misc_utils
80  * @title: Miscellaneous Utility Functions
81  * @short_description: a selection of portable utility functions
82  *
83  * These are portable utility functions.
84  */
85
86 #ifdef G_PLATFORM_WIN32
87 #  include <windows.h>
88 #  ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
89 #    define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
90 #    define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
91 #  endif
92 #  include <lmcons.h>           /* For UNLEN */
93 #endif /* G_PLATFORM_WIN32 */
94
95 #ifdef G_OS_WIN32
96 #  include <direct.h>
97 #  include <shlobj.h>
98 #  include <process.h>
99 #endif
100
101 #ifdef HAVE_CODESET
102 #include <langinfo.h>
103 #endif
104
105 #ifdef G_PLATFORM_WIN32
106
107 gchar *
108 _glib_get_dll_directory (void)
109 {
110   gchar *retval;
111   gchar *p;
112   wchar_t wc_fn[MAX_PATH];
113
114 #ifdef DLL_EXPORT
115   if (glib_dll == NULL)
116     return NULL;
117 #endif
118
119   /* This code is different from that in
120    * g_win32_get_package_installation_directory_of_module() in that
121    * here we return the actual folder where the GLib DLL is. We don't
122    * do the check for it being in a "bin" or "lib" subfolder and then
123    * returning the parent of that.
124    *
125    * In a statically built GLib, glib_dll will be NULL and we will
126    * thus look up the application's .exe file's location.
127    */
128   if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
129     return NULL;
130
131   retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
132
133   p = strrchr (retval, G_DIR_SEPARATOR);
134   if (p == NULL)
135     {
136       /* Wtf? */
137       return NULL;
138     }
139   *p = '\0';
140
141   return retval;
142 }
143
144 #endif
145
146 /**
147  * g_memmove: 
148  * @dest: the destination address to copy the bytes to.
149  * @src: the source address to copy the bytes from.
150  * @len: the number of bytes to copy.
151  *
152  * Copies a block of memory @len bytes long, from @src to @dest.
153  * The source and destination areas may overlap.
154  *
155  * Deprecated:2.40: Just use memmove().
156  */
157
158 #ifdef G_OS_WIN32
159 #undef g_atexit
160 #endif
161
162 /**
163  * g_atexit:
164  * @func: (scope async): the function to call on normal program termination.
165  * 
166  * Specifies a function to be called at normal program termination.
167  *
168  * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
169  * macro that maps to a call to the atexit() function in the C
170  * library. This means that in case the code that calls g_atexit(),
171  * i.e. atexit(), is in a DLL, the function will be called when the
172  * DLL is detached from the program. This typically makes more sense
173  * than that the function is called when the GLib DLL is detached,
174  * which happened earlier when g_atexit() was a function in the GLib
175  * DLL.
176  *
177  * The behaviour of atexit() in the context of dynamically loaded
178  * modules is not formally specified and varies wildly.
179  *
180  * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
181  * loaded module which is unloaded before the program terminates might
182  * well cause a crash at program exit.
183  *
184  * Some POSIX systems implement atexit() like Windows, and have each
185  * dynamically loaded module maintain an own atexit chain that is
186  * called when the module is unloaded.
187  *
188  * On other POSIX systems, before a dynamically loaded module is
189  * unloaded, the registered atexit functions (if any) residing in that
190  * module are called, regardless where the code that registered them
191  * resided. This is presumably the most robust approach.
192  *
193  * As can be seen from the above, for portability it's best to avoid
194  * calling g_atexit() (or atexit()) except in the main executable of a
195  * program.
196  *
197  * Deprecated:2.32: It is best to avoid g_atexit().
198  */
199 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
200 void
201 g_atexit (GVoidFunc func)
202 {
203   gint result;
204   int errsv;
205
206   result = atexit ((void (*)(void)) func);
207   errsv = errno;
208   if (result)
209     {
210       g_error ("Could not register atexit() function: %s",
211                g_strerror (errsv));
212     }
213 }
214 G_GNUC_END_IGNORE_DEPRECATIONS
215
216 /* Based on execvp() from GNU Libc.
217  * Some of this code is cut-and-pasted into gspawn.c
218  */
219
220 static gchar*
221 my_strchrnul (const gchar *str, 
222               gchar        c)
223 {
224   gchar *p = (gchar*)str;
225   while (*p && (*p != c))
226     ++p;
227
228   return p;
229 }
230
231 #ifdef G_OS_WIN32
232
233 static gchar *inner_find_program_in_path (const gchar *program);
234
235 gchar*
236 g_find_program_in_path (const gchar *program)
237 {
238   const gchar *last_dot = strrchr (program, '.');
239
240   if (last_dot == NULL ||
241       strchr (last_dot, '\\') != NULL ||
242       strchr (last_dot, '/') != NULL)
243     {
244       const gint program_length = strlen (program);
245       gchar *pathext = g_build_path (";",
246                                      ".exe;.cmd;.bat;.com",
247                                      g_getenv ("PATHEXT"),
248                                      NULL);
249       gchar *p;
250       gchar *decorated_program;
251       gchar *retval;
252
253       p = pathext;
254       do
255         {
256           gchar *q = my_strchrnul (p, ';');
257
258           decorated_program = g_malloc (program_length + (q-p) + 1);
259           memcpy (decorated_program, program, program_length);
260           memcpy (decorated_program+program_length, p, q-p);
261           decorated_program [program_length + (q-p)] = '\0';
262           
263           retval = inner_find_program_in_path (decorated_program);
264           g_free (decorated_program);
265
266           if (retval != NULL)
267             {
268               g_free (pathext);
269               return retval;
270             }
271           p = q;
272         } while (*p++ != '\0');
273       g_free (pathext);
274       return NULL;
275     }
276   else
277     return inner_find_program_in_path (program);
278 }
279
280 #endif
281
282 /**
283  * g_find_program_in_path:
284  * @program: (type filename): a program name in the GLib file name encoding
285  * 
286  * Locates the first executable named @program in the user's path, in the
287  * same way that execvp() would locate it. Returns an allocated string
288  * with the absolute path name, or %NULL if the program is not found in
289  * the path. If @program is already an absolute path, returns a copy of
290  * @program if @program exists and is executable, and %NULL otherwise.
291  *  
292  * On Windows, if @program does not have a file type suffix, tries
293  * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
294  * the `PATHEXT` environment variable. 
295  * 
296  * On Windows, it looks for the file in the same way as CreateProcess() 
297  * would. This means first in the directory where the executing
298  * program was loaded from, then in the current directory, then in the
299  * Windows 32-bit system directory, then in the Windows directory, and
300  * finally in the directories in the `PATH` environment variable. If
301  * the program is found, the return value contains the full name
302  * including the type suffix.
303  *
304  * Returns: (type filename): a newly-allocated string with the absolute path,
305  *     or %NULL
306  **/
307 #ifdef G_OS_WIN32
308 static gchar *
309 inner_find_program_in_path (const gchar *program)
310 #else
311 gchar*
312 g_find_program_in_path (const gchar *program)
313 #endif
314 {
315   const gchar *path, *p;
316   gchar *name, *freeme;
317 #ifdef G_OS_WIN32
318   const gchar *path_copy;
319   gchar *filename = NULL, *appdir = NULL;
320   gchar *sysdir = NULL, *windir = NULL;
321   int n;
322   wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
323     wwindir[MAXPATHLEN];
324 #endif
325   gsize len;
326   gsize pathlen;
327
328   g_return_val_if_fail (program != NULL, NULL);
329
330   /* If it is an absolute path, or a relative path including subdirectories,
331    * don't look in PATH.
332    */
333   if (g_path_is_absolute (program)
334       || strchr (program, G_DIR_SEPARATOR) != NULL
335 #ifdef G_OS_WIN32
336       || strchr (program, '/') != NULL
337 #endif
338       )
339     {
340       if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
341           !g_file_test (program, G_FILE_TEST_IS_DIR))
342         return g_strdup (program);
343       else
344         return NULL;
345     }
346   
347   path = g_getenv ("PATH");
348 #if defined(G_OS_UNIX)
349   if (path == NULL)
350     {
351       /* There is no 'PATH' in the environment.  The default
352        * search path in GNU libc is the current directory followed by
353        * the path 'confstr' returns for '_CS_PATH'.
354        */
355       
356       /* In GLib we put . last, for security, and don't use the
357        * unportable confstr(); UNIX98 does not actually specify
358        * what to search if PATH is unset. POSIX may, dunno.
359        */
360       
361       path = "/bin:/usr/bin:.";
362     }
363 #else
364   n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
365   if (n > 0 && n < MAXPATHLEN)
366     filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
367   
368   n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
369   if (n > 0 && n < MAXPATHLEN)
370     sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
371   
372   n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
373   if (n > 0 && n < MAXPATHLEN)
374     windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
375   
376   if (filename)
377     {
378       appdir = g_path_get_dirname (filename);
379       g_free (filename);
380     }
381   
382   path = g_strdup (path);
383
384   if (windir)
385     {
386       const gchar *tem = path;
387       path = g_strconcat (windir, ";", path, NULL);
388       g_free ((gchar *) tem);
389       g_free (windir);
390     }
391   
392   if (sysdir)
393     {
394       const gchar *tem = path;
395       path = g_strconcat (sysdir, ";", path, NULL);
396       g_free ((gchar *) tem);
397       g_free (sysdir);
398     }
399   
400   {
401     const gchar *tem = path;
402     path = g_strconcat (".;", path, NULL);
403     g_free ((gchar *) tem);
404   }
405   
406   if (appdir)
407     {
408       const gchar *tem = path;
409       path = g_strconcat (appdir, ";", path, NULL);
410       g_free ((gchar *) tem);
411       g_free (appdir);
412     }
413
414   path_copy = path;
415 #endif
416   
417   len = strlen (program) + 1;
418   pathlen = strlen (path);
419   freeme = name = g_malloc (pathlen + len + 1);
420   
421   /* Copy the file name at the top, including '\0'  */
422   memcpy (name + pathlen + 1, program, len);
423   name = name + pathlen;
424   /* And add the slash before the filename  */
425   *name = G_DIR_SEPARATOR;
426   
427   p = path;
428   do
429     {
430       char *startp;
431
432       path = p;
433       p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
434
435       if (p == path)
436         /* Two adjacent colons, or a colon at the beginning or the end
437          * of 'PATH' means to search the current directory.
438          */
439         startp = name + 1;
440       else
441         startp = memcpy (name - (p - path), path, p - path);
442
443       if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
444           !g_file_test (startp, G_FILE_TEST_IS_DIR))
445         {
446           gchar *ret;
447           ret = g_strdup (startp);
448           g_free (freeme);
449 #ifdef G_OS_WIN32
450           g_free ((gchar *) path_copy);
451 #endif
452           return ret;
453         }
454     }
455   while (*p++ != '\0');
456   
457   g_free (freeme);
458 #ifdef G_OS_WIN32
459   g_free ((gchar *) path_copy);
460 #endif
461
462   return NULL;
463 }
464
465 /* The functions below are defined this way for compatibility reasons.
466  * See the note in gutils.h.
467  */
468
469 /**
470  * g_bit_nth_lsf:
471  * @mask: a #gulong containing flags
472  * @nth_bit: the index of the bit to start the search from
473  *
474  * Find the position of the first bit set in @mask, searching
475  * from (but not including) @nth_bit upwards. Bits are numbered
476  * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
477  * usually). To start searching from the 0th bit, set @nth_bit to -1.
478  *
479  * Returns: the index of the first bit set which is higher than @nth_bit, or -1
480  *    if no higher bits are set
481  */
482 gint
483 (g_bit_nth_lsf) (gulong mask,
484                  gint   nth_bit)
485 {
486   return g_bit_nth_lsf_impl (mask, nth_bit);
487 }
488
489 /**
490  * g_bit_nth_msf:
491  * @mask: a #gulong containing flags
492  * @nth_bit: the index of the bit to start the search from
493  *
494  * Find the position of the first bit set in @mask, searching
495  * from (but not including) @nth_bit downwards. Bits are numbered
496  * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
497  * usually). To start searching from the last bit, set @nth_bit to
498  * -1 or GLIB_SIZEOF_LONG * 8.
499  *
500  * Returns: the index of the first bit set which is lower than @nth_bit, or -1
501  *    if no lower bits are set
502  */
503 gint
504 (g_bit_nth_msf) (gulong mask,
505                  gint   nth_bit)
506 {
507   return g_bit_nth_msf_impl (mask, nth_bit);
508 }
509
510
511 /**
512  * g_bit_storage:
513  * @number: a #guint
514  *
515  * Gets the number of bits used to hold @number,
516  * e.g. if @number is 4, 3 bits are needed.
517  *
518  * Returns: the number of bits used to hold @number
519  */
520 guint
521 (g_bit_storage) (gulong number)
522 {
523   return g_bit_storage_impl (number);
524 }
525
526 G_LOCK_DEFINE_STATIC (g_utils_global);
527
528 typedef struct
529 {
530   gchar *user_name;
531   gchar *real_name;
532   gchar *home_dir;
533 } UserDatabaseEntry;
534
535 /* These must all be read/written with @g_utils_global held. */
536 static  gchar   *g_user_data_dir = NULL;
537 static  gchar  **g_system_data_dirs = NULL;
538 static  gchar   *g_user_cache_dir = NULL;
539 static  gchar   *g_user_config_dir = NULL;
540 static  gchar   *g_user_runtime_dir = NULL;
541 static  gchar  **g_system_config_dirs = NULL;
542 static  gchar  **g_user_special_dirs = NULL;
543
544 /* fifteen minutes of fame for everybody */
545 #define G_USER_DIRS_EXPIRE      15 * 60
546
547 #ifdef G_OS_WIN32
548
549 static gchar *
550 get_special_folder (int csidl)
551 {
552   wchar_t path[MAX_PATH+1];
553   HRESULT hr;
554   LPITEMIDLIST pidl = NULL;
555   BOOL b;
556   gchar *retval = NULL;
557
558   hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
559   if (hr == S_OK)
560     {
561       b = SHGetPathFromIDListW (pidl, path);
562       if (b)
563         retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
564       CoTaskMemFree (pidl);
565     }
566   return retval;
567 }
568
569 static char *
570 get_windows_directory_root (void)
571 {
572   wchar_t wwindowsdir[MAX_PATH];
573
574   if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
575     {
576       /* Usually X:\Windows, but in terminal server environments
577        * might be an UNC path, AFAIK.
578        */
579       char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
580       char *p;
581
582       if (windowsdir == NULL)
583         return g_strdup ("C:\\");
584
585       p = (char *) g_path_skip_root (windowsdir);
586       if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
587         p--;
588       *p = '\0';
589       return windowsdir;
590     }
591   else
592     return g_strdup ("C:\\");
593 }
594
595 #endif
596
597 /* HOLDS: g_utils_global_lock */
598 static UserDatabaseEntry *
599 g_get_user_database_entry (void)
600 {
601   static UserDatabaseEntry *entry;
602
603   if (g_once_init_enter (&entry))
604     {
605       static UserDatabaseEntry e;
606
607 #ifdef G_OS_UNIX
608       {
609         struct passwd *pw = NULL;
610         gpointer buffer = NULL;
611         gint error;
612         gchar *logname;
613
614 #  if defined (HAVE_GETPWUID_R)
615         struct passwd pwd;
616 #    ifdef _SC_GETPW_R_SIZE_MAX
617         /* This reurns the maximum length */
618         glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
619
620         if (bufsize < 0)
621           bufsize = 64;
622 #    else /* _SC_GETPW_R_SIZE_MAX */
623         glong bufsize = 64;
624 #    endif /* _SC_GETPW_R_SIZE_MAX */
625
626         logname = (gchar *) g_getenv ("LOGNAME");
627
628         do
629           {
630             g_free (buffer);
631             /* we allocate 6 extra bytes to work around a bug in
632              * Mac OS < 10.3. See #156446
633              */
634             buffer = g_malloc (bufsize + 6);
635             errno = 0;
636
637             if (logname) {
638               error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
639               if (!pw || (pw->pw_uid != getuid ())) {
640                 /* LOGNAME is lying, fall back to looking up the uid */
641                 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
642               }
643             } else {
644               error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
645             }
646             error = error < 0 ? errno : error;
647
648             if (!pw)
649               {
650                 /* we bail out prematurely if the user id can't be found
651                  * (should be pretty rare case actually), or if the buffer
652                  * should be sufficiently big and lookups are still not
653                  * successful.
654                  */
655                 if (error == 0 || error == ENOENT)
656                   {
657                     g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
658                                (gulong) getuid ());
659                     break;
660                   }
661                 if (bufsize > 32 * 1024)
662                   {
663                     g_warning ("getpwuid_r(): failed due to: %s.",
664                                g_strerror (error));
665                     break;
666                   }
667
668                 bufsize *= 2;
669               }
670           }
671         while (!pw);
672 #  endif /* HAVE_GETPWUID_R */
673
674         if (!pw)
675           {
676             pw = getpwuid (getuid ());
677           }
678         if (pw)
679           {
680             e.user_name = g_strdup (pw->pw_name);
681
682 #ifndef __BIONIC__
683             if (pw->pw_gecos && *pw->pw_gecos != '\0')
684               {
685                 gchar **gecos_fields;
686                 gchar **name_parts;
687
688                 /* split the gecos field and substitute '&' */
689                 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
690                 name_parts = g_strsplit (gecos_fields[0], "&", 0);
691                 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
692                 e.real_name = g_strjoinv (pw->pw_name, name_parts);
693                 g_strfreev (gecos_fields);
694                 g_strfreev (name_parts);
695               }
696 #endif
697
698             if (!e.home_dir)
699               e.home_dir = g_strdup (pw->pw_dir);
700           }
701         g_free (buffer);
702       }
703
704 #endif /* G_OS_UNIX */
705
706 #ifdef G_OS_WIN32
707       {
708         guint len = UNLEN+1;
709         wchar_t buffer[UNLEN+1];
710
711         if (GetUserNameW (buffer, (LPDWORD) &len))
712           {
713             e.user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
714             e.real_name = g_strdup (e.user_name);
715           }
716       }
717 #endif /* G_OS_WIN32 */
718
719       if (!e.user_name)
720         e.user_name = g_strdup ("somebody");
721       if (!e.real_name)
722         e.real_name = g_strdup ("Unknown");
723
724       g_once_init_leave (&entry, &e);
725     }
726
727   return entry;
728 }
729
730 /**
731  * g_get_user_name:
732  *
733  * Gets the user name of the current user. The encoding of the returned
734  * string is system-defined. On UNIX, it might be the preferred file name
735  * encoding, or something else, and there is no guarantee that it is even
736  * consistent on a machine. On Windows, it is always UTF-8.
737  *
738  * Returns: (type filename): the user name of the current user.
739  */
740 const gchar *
741 g_get_user_name (void)
742 {
743   UserDatabaseEntry *entry;
744
745   entry = g_get_user_database_entry ();
746
747   return entry->user_name;
748 }
749
750 /**
751  * g_get_real_name:
752  *
753  * Gets the real name of the user. This usually comes from the user's
754  * entry in the `passwd` file. The encoding of the returned string is
755  * system-defined. (On Windows, it is, however, always UTF-8.) If the
756  * real user name cannot be determined, the string "Unknown" is 
757  * returned.
758  *
759  * Returns: (type filename): the user's real name.
760  */
761 const gchar *
762 g_get_real_name (void)
763 {
764   UserDatabaseEntry *entry;
765
766   entry = g_get_user_database_entry ();
767
768   return entry->real_name;
769 }
770
771 /* Protected by @g_utils_global_lock. */
772 static gchar *g_home_dir = NULL;  /* (owned) (nullable before initialised) */
773
774 static gchar *
775 g_build_home_dir (void)
776 {
777   gchar *home_dir;
778
779   /* We first check HOME and use it if it is set */
780   home_dir = g_strdup (g_getenv ("HOME"));
781
782 #ifdef G_OS_WIN32
783   /* Only believe HOME if it is an absolute path and exists.
784    *
785    * We only do this check on Windows for a couple of reasons.
786    * Historically, we only did it there because we used to ignore $HOME
787    * on UNIX.  There are concerns about enabling it now on UNIX because
788    * of things like autofs.  In short, if the user has a bogus value in
789    * $HOME then they get what they pay for...
790    */
791   if (home_dir != NULL)
792     {
793       if (!(g_path_is_absolute (home_dir) &&
794             g_file_test (home_dir, G_FILE_TEST_IS_DIR)))
795         g_clear_pointer (&home_dir, g_free);
796     }
797
798   /* In case HOME is Unix-style (it happens), convert it to
799    * Windows style.
800    */
801   if (home_dir != NULL)
802     {
803       gchar *p;
804       while ((p = strchr (home_dir, '/')) != NULL)
805         *p = '\\';
806     }
807
808   if (home_dir == NULL)
809     {
810       /* USERPROFILE is probably the closest equivalent to $HOME? */
811       if (g_getenv ("USERPROFILE") != NULL)
812         home_dir = g_strdup (g_getenv ("USERPROFILE"));
813     }
814
815   if (home_dir == NULL)
816     home_dir = get_special_folder (CSIDL_PROFILE);
817
818   if (home_dir == NULL)
819     home_dir = get_windows_directory_root ();
820 #endif /* G_OS_WIN32 */
821
822   if (home_dir == NULL)
823     {
824       /* If we didn't get it from any of those methods, we will have
825        * to read the user database entry.
826        */
827       UserDatabaseEntry *entry = g_get_user_database_entry ();
828       home_dir = g_strdup (entry->home_dir);
829     }
830
831   /* If we have been denied access to /etc/passwd (for example, by an
832    * overly-zealous LSM), make up a junk value. The return value at this
833    * point is explicitly documented as â€˜undefined’. */
834   if (home_dir == NULL)
835     {
836       g_warning ("Could not find home directory: $HOME is not set, and "
837                  "user database could not be read.");
838       home_dir = g_strdup ("/");
839     }
840
841   return g_steal_pointer (&home_dir);
842 }
843
844 /**
845  * g_get_home_dir:
846  *
847  * Gets the current user's home directory.
848  *
849  * As with most UNIX tools, this function will return the value of the
850  * `HOME` environment variable if it is set to an existing absolute path
851  * name, falling back to the `passwd` file in the case that it is unset.
852  *
853  * If the path given in `HOME` is non-absolute, does not exist, or is
854  * not a directory, the result is undefined.
855  *
856  * Before version 2.36 this function would ignore the `HOME` environment
857  * variable, taking the value from the `passwd` database instead. This was
858  * changed to increase the compatibility of GLib with other programs (and
859  * the XDG basedir specification) and to increase testability of programs
860  * based on GLib (by making it easier to run them from test frameworks).
861  *
862  * If your program has a strong requirement for either the new or the
863  * old behaviour (and if you don't wish to increase your GLib
864  * dependency to ensure that the new behaviour is in effect) then you
865  * should either directly check the `HOME` environment variable yourself
866  * or unset it before calling any functions in GLib.
867  *
868  * Returns: (type filename): the current user's home directory
869  */
870 const gchar *
871 g_get_home_dir (void)
872 {
873   const gchar *home_dir;
874
875   G_LOCK (g_utils_global);
876
877   if (g_home_dir == NULL)
878     g_home_dir = g_build_home_dir ();
879   home_dir = g_home_dir;
880
881   G_UNLOCK (g_utils_global);
882
883   return home_dir;
884 }
885
886 /**
887  * g_get_tmp_dir:
888  *
889  * Gets the directory to use for temporary files.
890  *
891  * On UNIX, this is taken from the `TMPDIR` environment variable.
892  * If the variable is not set, `P_tmpdir` is
893  * used, as defined by the system C library. Failing that, a
894  * hard-coded default of "/tmp" is returned.
895  *
896  * On Windows, the `TEMP` environment variable is used, with the
897  * root directory of the Windows installation (eg: "C:\") used
898  * as a default.
899  *
900  * The encoding of the returned string is system-defined. On Windows,
901  * it is always UTF-8. The return value is never %NULL or the empty
902  * string.
903  *
904  * Returns: (type filename): the directory to use for temporary files.
905  */
906 const gchar *
907 g_get_tmp_dir (void)
908 {
909   static gchar *tmp_dir;
910
911   if (g_once_init_enter (&tmp_dir))
912     {
913       gchar *tmp;
914
915 #ifdef G_OS_WIN32
916       tmp = g_strdup (g_getenv ("TEMP"));
917
918       if (tmp == NULL || *tmp == '\0')
919         {
920           g_free (tmp);
921           tmp = get_windows_directory_root ();
922         }
923 #else /* G_OS_WIN32 */
924       tmp = g_strdup (g_getenv ("TMPDIR"));
925
926 #ifdef P_tmpdir
927       if (tmp == NULL || *tmp == '\0')
928         {
929           gsize k;
930           g_free (tmp);
931           tmp = g_strdup (P_tmpdir);
932           k = strlen (tmp);
933           if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
934             tmp[k - 1] = '\0';
935         }
936 #endif /* P_tmpdir */
937
938       if (tmp == NULL || *tmp == '\0')
939         {
940           g_free (tmp);
941           tmp = g_strdup ("/tmp");
942         }
943 #endif /* !G_OS_WIN32 */
944
945       g_once_init_leave (&tmp_dir, tmp);
946     }
947
948   return tmp_dir;
949 }
950
951 /**
952  * g_get_host_name:
953  *
954  * Return a name for the machine. 
955  *
956  * The returned name is not necessarily a fully-qualified domain name,
957  * or even present in DNS or some other name service at all. It need
958  * not even be unique on your local network or site, but usually it
959  * is. Callers should not rely on the return value having any specific
960  * properties like uniqueness for security purposes. Even if the name
961  * of the machine is changed while an application is running, the
962  * return value from this function does not change. The returned
963  * string is owned by GLib and should not be modified or freed. If no
964  * name can be determined, a default fixed string "localhost" is
965  * returned.
966  *
967  * The encoding of the returned string is UTF-8.
968  *
969  * Returns: the host name of the machine.
970  *
971  * Since: 2.8
972  */
973 const gchar *
974 g_get_host_name (void)
975 {
976   static gchar *hostname;
977
978   if (g_once_init_enter (&hostname))
979     {
980       gboolean failed;
981       gchar *utmp;
982
983 #ifndef G_OS_WIN32
984       glong max;
985       gsize size;
986       /* The number 256 * 256 is taken from the value of _POSIX_HOST_NAME_MAX,
987        * which is 255. Since we use _POSIX_HOST_NAME_MAX + 1 (= 256) in the
988        * fallback case, we pick 256 * 256 as the size of the larger buffer here.
989        * It should be large enough. It doesn't looks reasonable to name a host
990        * with a string that is longer than 64 KiB.
991        */
992       const gsize size_large = (gsize) 256 * 256;
993       gchar *tmp;
994
995       max = sysconf (_SC_HOST_NAME_MAX);
996       if (max > 0 && max <= G_MAXSIZE - 1)
997         size = (gsize) max + 1;
998       else
999 #ifdef HOST_NAME_MAX
1000         size = HOST_NAME_MAX + 1;
1001 #else
1002         size = _POSIX_HOST_NAME_MAX + 1;
1003 #endif
1004
1005       tmp = g_malloc (size);
1006       failed = (gethostname (tmp, size) == -1);
1007       if (failed && size < size_large)
1008         {
1009           /* Try again with a larger buffer if 'size' may be too small. */
1010           g_free (tmp);
1011           tmp = g_malloc (size_large);
1012           failed = (gethostname (tmp, size_large) == -1);
1013         }
1014
1015       if (failed)
1016         g_clear_pointer (&tmp, g_free);
1017       utmp = tmp;
1018 #else
1019       wchar_t tmp[MAX_COMPUTERNAME_LENGTH + 1];
1020       DWORD size = sizeof (tmp) / sizeof (tmp[0]);
1021       failed = (!GetComputerNameW (tmp, &size));
1022       if (!failed)
1023         utmp = g_utf16_to_utf8 (tmp, size, NULL, NULL, NULL);
1024       if (utmp == NULL)
1025         failed = TRUE;
1026 #endif
1027
1028       g_once_init_leave (&hostname, failed ? g_strdup ("localhost") : utmp);
1029     }
1030
1031   return hostname;
1032 }
1033
1034 G_LOCK_DEFINE_STATIC (g_prgname);
1035 static gchar *g_prgname = NULL;
1036
1037 /**
1038  * g_get_prgname:
1039  *
1040  * Gets the name of the program. This name should not be localized,
1041  * in contrast to g_get_application_name().
1042  *
1043  * If you are using #GApplication the program name is set in
1044  * g_application_run(). In case of GDK or GTK+ it is set in
1045  * gdk_init(), which is called by gtk_init() and the
1046  * #GtkApplication::startup handler. The program name is found by
1047  * taking the last component of @argv[0].
1048  *
1049  * Returns: (nullable): the name of the program, or %NULL if it has not been
1050  *     set yet. The returned string belongs
1051  *     to GLib and must not be modified or freed.
1052  */
1053 const gchar*
1054 g_get_prgname (void)
1055 {
1056   gchar* retval;
1057
1058   G_LOCK (g_prgname);
1059   retval = g_prgname;
1060   G_UNLOCK (g_prgname);
1061
1062   return retval;
1063 }
1064
1065 /**
1066  * g_set_prgname:
1067  * @prgname: the name of the program.
1068  *
1069  * Sets the name of the program. This name should not be localized,
1070  * in contrast to g_set_application_name().
1071  *
1072  * If you are using #GApplication the program name is set in
1073  * g_application_run(). In case of GDK or GTK+ it is set in
1074  * gdk_init(), which is called by gtk_init() and the
1075  * #GtkApplication::startup handler. The program name is found by
1076  * taking the last component of @argv[0].
1077  *
1078  * Note that for thread-safety reasons this function can only be called once.
1079  */
1080 void
1081 g_set_prgname (const gchar *prgname)
1082 {
1083   G_LOCK (g_prgname);
1084   g_free (g_prgname);
1085   g_prgname = g_strdup (prgname);
1086   G_UNLOCK (g_prgname);
1087 }
1088
1089 G_LOCK_DEFINE_STATIC (g_application_name);
1090 static gchar *g_application_name = NULL;
1091
1092 /**
1093  * g_get_application_name:
1094  * 
1095  * Gets a human-readable name for the application, as set by
1096  * g_set_application_name(). This name should be localized if
1097  * possible, and is intended for display to the user.  Contrast with
1098  * g_get_prgname(), which gets a non-localized name. If
1099  * g_set_application_name() has not been called, returns the result of
1100  * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1101  * been called).
1102  * 
1103  * Returns: human-readable application name. may return %NULL
1104  *
1105  * Since: 2.2
1106  **/
1107 const gchar *
1108 g_get_application_name (void)
1109 {
1110   gchar* retval;
1111
1112   G_LOCK (g_application_name);
1113   retval = g_application_name;
1114   G_UNLOCK (g_application_name);
1115
1116   if (retval == NULL)
1117     return g_get_prgname ();
1118   
1119   return retval;
1120 }
1121
1122 /**
1123  * g_set_application_name:
1124  * @application_name: localized name of the application
1125  *
1126  * Sets a human-readable name for the application. This name should be
1127  * localized if possible, and is intended for display to the user.
1128  * Contrast with g_set_prgname(), which sets a non-localized name.
1129  * g_set_prgname() will be called automatically by gtk_init(),
1130  * but g_set_application_name() will not.
1131  *
1132  * Note that for thread safety reasons, this function can only
1133  * be called once.
1134  *
1135  * The application name will be used in contexts such as error messages,
1136  * or when displaying an application's name in the task list.
1137  * 
1138  * Since: 2.2
1139  **/
1140 void
1141 g_set_application_name (const gchar *application_name)
1142 {
1143   gboolean already_set = FALSE;
1144         
1145   G_LOCK (g_application_name);
1146   if (g_application_name)
1147     already_set = TRUE;
1148   else
1149     g_application_name = g_strdup (application_name);
1150   G_UNLOCK (g_application_name);
1151
1152   if (already_set)
1153     g_warning ("g_set_application_name() called multiple times");
1154 }
1155
1156 /* Set @global_str to a copy of @new_value if it’s currently unset or has a
1157  * different value. If its current value matches @new_value, do nothing. If
1158  * replaced, we have to leak the old value as client code could still have
1159  * pointers to it. */
1160 static void
1161 set_str_if_different (gchar       **global_str,
1162                       const gchar  *type,
1163                       const gchar  *new_value)
1164 {
1165   if (*global_str == NULL ||
1166       !g_str_equal (new_value, *global_str))
1167     {
1168       g_debug ("g_set_user_dirs: Setting %s to %s", type, new_value);
1169
1170       /* We have to leak the old value, as user code could be retaining pointers
1171        * to it. */
1172       *global_str = g_strdup (new_value);
1173     }
1174 }
1175
1176 static void
1177 set_strv_if_different (gchar                ***global_strv,
1178                        const gchar            *type,
1179                        const gchar  * const   *new_value)
1180 {
1181   if (*global_strv == NULL ||
1182       !g_strv_equal (new_value, (const gchar * const *) *global_strv))
1183     {
1184       gchar *new_value_str = g_strjoinv (":", (gchar **) new_value);
1185       g_debug ("g_set_user_dirs: Setting %s to %s", type, new_value_str);
1186       g_free (new_value_str);
1187
1188       /* We have to leak the old value, as user code could be retaining pointers
1189        * to it. */
1190       *global_strv = g_strdupv ((gchar **) new_value);
1191     }
1192 }
1193
1194 /*
1195  * g_set_user_dirs:
1196  * @first_dir_type: Type of the first directory to set
1197  * @...: Value to set the first directory to, followed by additional type/value
1198  *    pairs, followed by %NULL
1199  *
1200  * Set one or more â€˜user’ directories to custom values. This is intended to be
1201  * used by test code (particularly with the %G_TEST_OPTION_ISOLATE_DIRS option)
1202  * to override the values returned by the following functions, so that test
1203  * code can be run without touching an installed system and user data:
1204  *
1205  *  - g_get_home_dir() â€” use type `HOME`, pass a string
1206  *  - g_get_user_cache_dir() â€” use type `XDG_CACHE_HOME`, pass a string
1207  *  - g_get_system_config_dirs() â€” use type `XDG_CONFIG_DIRS`, pass a
1208  *    %NULL-terminated string array
1209  *  - g_get_user_config_dir() â€” use type `XDG_CONFIG_HOME`, pass a string
1210  *  - g_get_system_data_dirs() â€” use type `XDG_DATA_DIRS`, pass a
1211  *    %NULL-terminated string array
1212  *  - g_get_user_data_dir() â€” use type `XDG_DATA_HOME`, pass a string
1213  *  - g_get_user_runtime_dir() â€” use type `XDG_RUNTIME_DIR`, pass a string
1214  *
1215  * The list must be terminated with a %NULL type. All of the values must be
1216  * non-%NULL â€” passing %NULL as a value won’t reset a directory. If a reference
1217  * to a directory from the calling environment needs to be kept, copy it before
1218  * the first call to g_set_user_dirs(). g_set_user_dirs() can be called multiple
1219  * times.
1220  *
1221  * Since: 2.60
1222  */
1223 /*< private > */
1224 void
1225 g_set_user_dirs (const gchar *first_dir_type,
1226                  ...)
1227 {
1228   va_list args;
1229   const gchar *dir_type;
1230
1231   G_LOCK (g_utils_global);
1232
1233   va_start (args, first_dir_type);
1234
1235   for (dir_type = first_dir_type; dir_type != NULL; dir_type = va_arg (args, const gchar *))
1236     {
1237       gconstpointer dir_value = va_arg (args, gconstpointer);
1238       g_assert (dir_value != NULL);
1239
1240       if (g_str_equal (dir_type, "HOME"))
1241         set_str_if_different (&g_home_dir, dir_type, dir_value);
1242       else if (g_str_equal (dir_type, "XDG_CACHE_HOME"))
1243         set_str_if_different (&g_user_cache_dir, dir_type, dir_value);
1244       else if (g_str_equal (dir_type, "XDG_CONFIG_DIRS"))
1245         set_strv_if_different (&g_system_config_dirs, dir_type, dir_value);
1246       else if (g_str_equal (dir_type, "XDG_CONFIG_HOME"))
1247         set_str_if_different (&g_user_config_dir, dir_type, dir_value);
1248       else if (g_str_equal (dir_type, "XDG_DATA_DIRS"))
1249         set_strv_if_different (&g_system_data_dirs, dir_type, dir_value);
1250       else if (g_str_equal (dir_type, "XDG_DATA_HOME"))
1251         set_str_if_different (&g_user_data_dir, dir_type, dir_value);
1252       else if (g_str_equal (dir_type, "XDG_RUNTIME_DIR"))
1253         set_str_if_different (&g_user_runtime_dir, dir_type, dir_value);
1254       else
1255         g_assert_not_reached ();
1256     }
1257
1258   va_end (args);
1259
1260   G_UNLOCK (g_utils_global);
1261 }
1262
1263 static gchar *
1264 g_build_user_data_dir (void)
1265 {
1266   gchar *data_dir = NULL;
1267   const gchar *data_dir_env = g_getenv ("XDG_DATA_HOME");
1268
1269   if (data_dir_env && data_dir_env[0])
1270     data_dir = g_strdup (data_dir_env);
1271 #ifdef G_OS_WIN32
1272   else
1273     data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1274 #endif
1275   if (!data_dir || !data_dir[0])
1276     {
1277       gchar *home_dir = g_build_home_dir ();
1278       data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1279       g_free (home_dir);
1280     }
1281
1282   return g_steal_pointer (&data_dir);
1283 }
1284
1285 /**
1286  * g_get_user_data_dir:
1287  * 
1288  * Returns a base directory in which to access application data such
1289  * as icons that is customized for a particular user.  
1290  *
1291  * On UNIX platforms this is determined using the mechanisms described
1292  * in the
1293  * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1294  * In this case the directory retrieved will be `XDG_DATA_HOME`.
1295  *
1296  * On Windows it follows XDG Base Directory Specification if `XDG_DATA_HOME`
1297  * is defined. If `XDG_DATA_HOME` is undefined, the folder to use for local (as
1298  * opposed to roaming) application data is used instead. See the
1299  * [documentation for `CSIDL_LOCAL_APPDATA`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_local_appdata).
1300  * Note that in this case on Windows it will be the same
1301  * as what g_get_user_config_dir() returns.
1302  *
1303  * Returns: (type filename): a string owned by GLib that must not be modified
1304  *               or freed.
1305  * Since: 2.6
1306  **/
1307 const gchar *
1308 g_get_user_data_dir (void)
1309 {
1310   const gchar *user_data_dir;
1311
1312   G_LOCK (g_utils_global);
1313
1314   if (g_user_data_dir == NULL)
1315     g_user_data_dir = g_build_user_data_dir ();
1316   user_data_dir = g_user_data_dir;
1317
1318   G_UNLOCK (g_utils_global);
1319
1320   return user_data_dir;
1321 }
1322
1323 static gchar *
1324 g_build_user_config_dir (void)
1325 {
1326   gchar *config_dir = NULL;
1327   const gchar *config_dir_env = g_getenv ("XDG_CONFIG_HOME");
1328
1329   if (config_dir_env && config_dir_env[0])
1330     config_dir = g_strdup (config_dir_env);
1331 #ifdef G_OS_WIN32
1332   else
1333     config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1334 #endif
1335   if (!config_dir || !config_dir[0])
1336     {
1337       gchar *home_dir = g_build_home_dir ();
1338       config_dir = g_build_filename (home_dir, ".config", NULL);
1339       g_free (home_dir);
1340     }
1341
1342   return g_steal_pointer (&config_dir);
1343 }
1344
1345 /**
1346  * g_get_user_config_dir:
1347  * 
1348  * Returns a base directory in which to store user-specific application 
1349  * configuration information such as user preferences and settings. 
1350  *
1351  * On UNIX platforms this is determined using the mechanisms described
1352  * in the
1353  * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1354  * In this case the directory retrieved will be `XDG_CONFIG_HOME`.
1355  *
1356  * On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_HOME` is defined.
1357  * If `XDG_CONFIG_HOME` is undefined, the folder to use for local (as opposed
1358  * to roaming) application data is used instead. See the
1359  * [documentation for `CSIDL_LOCAL_APPDATA`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_local_appdata).
1360  * Note that in this case on Windows it will be  the same
1361  * as what g_get_user_data_dir() returns.
1362  *
1363  * Returns: (type filename): a string owned by GLib that must not be modified
1364  *               or freed.
1365  * Since: 2.6
1366  **/
1367 const gchar *
1368 g_get_user_config_dir (void)
1369 {
1370   const gchar *user_config_dir;
1371
1372   G_LOCK (g_utils_global);
1373
1374   if (g_user_config_dir == NULL)
1375     g_user_config_dir = g_build_user_config_dir ();
1376   user_config_dir = g_user_config_dir;
1377
1378   G_UNLOCK (g_utils_global);
1379
1380   return user_config_dir;
1381 }
1382
1383 static gchar *
1384 g_build_user_cache_dir (void)
1385 {
1386   gchar *cache_dir = NULL;
1387   const gchar *cache_dir_env = g_getenv ("XDG_CACHE_HOME");
1388
1389   if (cache_dir_env && cache_dir_env[0])
1390     cache_dir = g_strdup (cache_dir_env);
1391 #ifdef G_OS_WIN32
1392   else
1393     cache_dir = get_special_folder (CSIDL_INTERNET_CACHE);
1394 #endif
1395   if (!cache_dir || !cache_dir[0])
1396     {
1397       gchar *home_dir = g_build_home_dir ();
1398       cache_dir = g_build_filename (home_dir, ".cache", NULL);
1399       g_free (home_dir);
1400     }
1401
1402   return g_steal_pointer (&cache_dir);
1403 }
1404
1405 /**
1406  * g_get_user_cache_dir:
1407  * 
1408  * Returns a base directory in which to store non-essential, cached
1409  * data specific to particular user.
1410  *
1411  * On UNIX platforms this is determined using the mechanisms described
1412  * in the
1413  * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1414  * In this case the directory retrieved will be `XDG_CACHE_HOME`.
1415  *
1416  * On Windows it follows XDG Base Directory Specification if `XDG_CACHE_HOME` is defined.
1417  * If `XDG_CACHE_HOME` is undefined, the directory that serves as a common
1418  * repository for temporary Internet files is used instead. A typical path is
1419  * `C:\Documents and Settings\username\Local Settings\Temporary Internet Files`.
1420  * See the [documentation for `CSIDL_INTERNET_CACHE`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494%28v=vs.85%29.aspx#csidl_internet_cache).
1421  *
1422  * Returns: (type filename): a string owned by GLib that must not be modified
1423  *               or freed.
1424  * Since: 2.6
1425  **/
1426 const gchar *
1427 g_get_user_cache_dir (void)
1428 {
1429   const gchar *user_cache_dir;
1430
1431   G_LOCK (g_utils_global);
1432
1433   if (g_user_cache_dir == NULL)
1434     g_user_cache_dir = g_build_user_cache_dir ();
1435   user_cache_dir = g_user_cache_dir;
1436
1437   G_UNLOCK (g_utils_global);
1438
1439   return user_cache_dir;
1440 }
1441
1442 static gchar *
1443 g_build_user_runtime_dir (void)
1444 {
1445   gchar *runtime_dir = NULL;
1446   const gchar *runtime_dir_env = g_getenv ("XDG_RUNTIME_DIR");
1447
1448   if (runtime_dir_env && runtime_dir_env[0])
1449     runtime_dir = g_strdup (runtime_dir_env);
1450   else
1451     {
1452       runtime_dir = g_build_user_cache_dir ();
1453
1454       /* The user should be able to rely on the directory existing
1455        * when the function returns.  Probably it already does, but
1456        * let's make sure.  Just do mkdir() directly since it will be
1457        * no more expensive than a stat() in the case that the
1458        * directory already exists and is a lot easier.
1459        *
1460        * $XDG_CACHE_HOME is probably ~/.cache/ so as long as $HOME
1461        * exists this will work.  If the user changed $XDG_CACHE_HOME
1462        * then they can make sure that it exists...
1463        */
1464       (void) g_mkdir (runtime_dir, 0700);
1465     }
1466
1467   return g_steal_pointer (&runtime_dir);
1468 }
1469
1470 /**
1471  * g_get_user_runtime_dir:
1472  *
1473  * Returns a directory that is unique to the current user on the local
1474  * system.
1475  *
1476  * This is determined using the mechanisms described
1477  * in the 
1478  * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1479  * This is the directory
1480  * specified in the `XDG_RUNTIME_DIR` environment variable.
1481  * In the case that this variable is not set, we return the value of
1482  * g_get_user_cache_dir(), after verifying that it exists.
1483  *
1484  * Returns: (type filename): a string owned by GLib that must not be
1485  *     modified or freed.
1486  *
1487  * Since: 2.28
1488  **/
1489 const gchar *
1490 g_get_user_runtime_dir (void)
1491 {
1492   const gchar *user_runtime_dir;
1493
1494   G_LOCK (g_utils_global);
1495
1496   if (g_user_runtime_dir == NULL)
1497     g_user_runtime_dir = g_build_user_runtime_dir ();
1498   user_runtime_dir = g_user_runtime_dir;
1499
1500   G_UNLOCK (g_utils_global);
1501
1502   return user_runtime_dir;
1503 }
1504
1505 #ifdef HAVE_COCOA
1506
1507 /* Implemented in gutils-macos.m */
1508 void load_user_special_dirs_macos (gchar **table);
1509
1510 static void
1511 load_user_special_dirs (void)
1512 {
1513   load_user_special_dirs_macos (g_user_special_dirs);
1514 }
1515
1516 #elif defined(G_OS_WIN32)
1517
1518 static void
1519 load_user_special_dirs (void)
1520 {
1521   typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1522                                                     DWORD dwFlags,
1523                                                     HANDLE hToken,
1524                                                     PWSTR *ppszPath);
1525   t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1526
1527   static const GUID FOLDERID_Downloads =
1528     { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1529   static const GUID FOLDERID_Public =
1530     { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1531
1532   wchar_t *wcp;
1533
1534   p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1535                                                                     "SHGetKnownFolderPath");
1536
1537   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1538   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1539
1540   if (p_SHGetKnownFolderPath == NULL)
1541     {
1542       g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1543     }
1544   else
1545     {
1546       wcp = NULL;
1547       (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1548       if (wcp)
1549         {
1550           g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1551           if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1552               g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1553           CoTaskMemFree (wcp);
1554         }
1555       else
1556           g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1557     }
1558
1559   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1560   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1561
1562   if (p_SHGetKnownFolderPath == NULL)
1563     {
1564       /* XXX */
1565       g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1566     }
1567   else
1568     {
1569       wcp = NULL;
1570       (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1571       if (wcp)
1572         {
1573           g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1574           if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1575               g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1576           CoTaskMemFree (wcp);
1577         }
1578       else
1579           g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1580     }
1581   
1582   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1583   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1584 }
1585
1586 #else /* default is unix */
1587
1588 /* adapted from xdg-user-dir-lookup.c
1589  *
1590  * Copyright (C) 2007 Red Hat Inc.
1591  *
1592  * Permission is hereby granted, free of charge, to any person
1593  * obtaining a copy of this software and associated documentation files
1594  * (the "Software"), to deal in the Software without restriction,
1595  * including without limitation the rights to use, copy, modify, merge,
1596  * publish, distribute, sublicense, and/or sell copies of the Software,
1597  * and to permit persons to whom the Software is furnished to do so,
1598  * subject to the following conditions: 
1599  *
1600  * The above copyright notice and this permission notice shall be
1601  * included in all copies or substantial portions of the Software. 
1602  *
1603  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1604  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1605  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1606  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1607  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1608  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1609  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1610  * SOFTWARE.
1611  */
1612 static void
1613 load_user_special_dirs (void)
1614 {
1615   gchar *config_dir = NULL;
1616   gchar *config_file;
1617   gchar *data;
1618   gchar **lines;
1619   gint n_lines, i;
1620   
1621   config_dir = g_build_user_config_dir ();
1622   config_file = g_build_filename (config_dir,
1623                                   "user-dirs.dirs",
1624                                   NULL);
1625   g_free (config_dir);
1626
1627   if (!g_file_get_contents (config_file, &data, NULL, NULL))
1628     {
1629       g_free (config_file);
1630       return;
1631     }
1632
1633   lines = g_strsplit (data, "\n", -1);
1634   n_lines = g_strv_length (lines);
1635   g_free (data);
1636   
1637   for (i = 0; i < n_lines; i++)
1638     {
1639       gchar *buffer = lines[i];
1640       gchar *d, *p;
1641       gint len;
1642       gboolean is_relative = FALSE;
1643       GUserDirectory directory;
1644
1645       /* Remove newline at end */
1646       len = strlen (buffer);
1647       if (len > 0 && buffer[len - 1] == '\n')
1648         buffer[len - 1] = 0;
1649       
1650       p = buffer;
1651       while (*p == ' ' || *p == '\t')
1652         p++;
1653       
1654       if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1655         {
1656           directory = G_USER_DIRECTORY_DESKTOP;
1657           p += strlen ("XDG_DESKTOP_DIR");
1658         }
1659       else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1660         {
1661           directory = G_USER_DIRECTORY_DOCUMENTS;
1662           p += strlen ("XDG_DOCUMENTS_DIR");
1663         }
1664       else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1665         {
1666           directory = G_USER_DIRECTORY_DOWNLOAD;
1667           p += strlen ("XDG_DOWNLOAD_DIR");
1668         }
1669       else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1670         {
1671           directory = G_USER_DIRECTORY_MUSIC;
1672           p += strlen ("XDG_MUSIC_DIR");
1673         }
1674       else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1675         {
1676           directory = G_USER_DIRECTORY_PICTURES;
1677           p += strlen ("XDG_PICTURES_DIR");
1678         }
1679       else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1680         {
1681           directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1682           p += strlen ("XDG_PUBLICSHARE_DIR");
1683         }
1684       else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1685         {
1686           directory = G_USER_DIRECTORY_TEMPLATES;
1687           p += strlen ("XDG_TEMPLATES_DIR");
1688         }
1689       else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1690         {
1691           directory = G_USER_DIRECTORY_VIDEOS;
1692           p += strlen ("XDG_VIDEOS_DIR");
1693         }
1694       else
1695         continue;
1696
1697       while (*p == ' ' || *p == '\t')
1698         p++;
1699
1700       if (*p != '=')
1701         continue;
1702       p++;
1703
1704       while (*p == ' ' || *p == '\t')
1705         p++;
1706
1707       if (*p != '"')
1708         continue;
1709       p++;
1710
1711       if (strncmp (p, "$HOME", 5) == 0)
1712         {
1713           p += 5;
1714           is_relative = TRUE;
1715         }
1716       else if (*p != '/')
1717         continue;
1718
1719       d = strrchr (p, '"');
1720       if (!d)
1721         continue;
1722       *d = 0;
1723
1724       d = p;
1725       
1726       /* remove trailing slashes */
1727       len = strlen (d);
1728       if (d[len - 1] == '/')
1729         d[len - 1] = 0;
1730       
1731       if (is_relative)
1732         {
1733           gchar *home_dir = g_build_home_dir ();
1734           g_user_special_dirs[directory] = g_build_filename (home_dir, d, NULL);
1735           g_free (home_dir);
1736         }
1737       else
1738         g_user_special_dirs[directory] = g_strdup (d);
1739     }
1740
1741   g_strfreev (lines);
1742   g_free (config_file);
1743 }
1744
1745 #endif /* platform-specific load_user_special_dirs implementations */
1746
1747
1748 /**
1749  * g_reload_user_special_dirs_cache:
1750  *
1751  * Resets the cache used for g_get_user_special_dir(), so
1752  * that the latest on-disk version is used. Call this only
1753  * if you just changed the data on disk yourself.
1754  *
1755  * Due to thread safety issues this may cause leaking of strings
1756  * that were previously returned from g_get_user_special_dir()
1757  * that can't be freed. We ensure to only leak the data for
1758  * the directories that actually changed value though.
1759  *
1760  * Since: 2.22
1761  */
1762 void
1763 g_reload_user_special_dirs_cache (void)
1764 {
1765   int i;
1766
1767   G_LOCK (g_utils_global);
1768
1769   if (g_user_special_dirs != NULL)
1770     {
1771       /* save a copy of the pointer, to check if some memory can be preserved */
1772       char **old_g_user_special_dirs = g_user_special_dirs;
1773       char *old_val;
1774
1775       /* recreate and reload our cache */
1776       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1777       load_user_special_dirs ();
1778
1779       /* only leak changed directories */
1780       for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1781         {
1782           old_val = old_g_user_special_dirs[i];
1783           if (g_user_special_dirs[i] == NULL)
1784             {
1785               g_user_special_dirs[i] = old_val;
1786             }
1787           else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1788             {
1789               /* don't leak */
1790               g_free (g_user_special_dirs[i]);
1791               g_user_special_dirs[i] = old_val;
1792             }
1793           else
1794             g_free (old_val);
1795         }
1796
1797       /* free the old array */
1798       g_free (old_g_user_special_dirs);
1799     }
1800
1801   G_UNLOCK (g_utils_global);
1802 }
1803
1804 /**
1805  * g_get_user_special_dir:
1806  * @directory: the logical id of special directory
1807  *
1808  * Returns the full path of a special directory using its logical id.
1809  *
1810  * On UNIX this is done using the XDG special user directories.
1811  * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1812  * falls back to `$HOME/Desktop` when XDG special user directories have
1813  * not been set up. 
1814  *
1815  * Depending on the platform, the user might be able to change the path
1816  * of the special directory without requiring the session to restart; GLib
1817  * will not reflect any change once the special directories are loaded.
1818  *
1819  * Returns: (type filename): the path to the specified special directory, or
1820  *   %NULL if the logical id was not found. The returned string is owned by
1821  *   GLib and should not be modified or freed.
1822  *
1823  * Since: 2.14
1824  */
1825 const gchar *
1826 g_get_user_special_dir (GUserDirectory directory)
1827 {
1828   const gchar *user_special_dir;
1829
1830   g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1831                         directory < G_USER_N_DIRECTORIES, NULL);
1832
1833   G_LOCK (g_utils_global);
1834
1835   if (G_UNLIKELY (g_user_special_dirs == NULL))
1836     {
1837       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1838
1839       load_user_special_dirs ();
1840
1841       /* Special-case desktop for historical compatibility */
1842       if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1843         {
1844           gchar *home_dir = g_build_home_dir ();
1845           g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (home_dir, "Desktop", NULL);
1846           g_free (home_dir);
1847         }
1848     }
1849   user_special_dir = g_user_special_dirs[directory];
1850
1851   G_UNLOCK (g_utils_global);
1852
1853   return user_special_dir;
1854 }
1855
1856 #ifdef G_OS_WIN32
1857
1858 #undef g_get_system_data_dirs
1859
1860 static HMODULE
1861 get_module_for_address (gconstpointer address)
1862 {
1863   /* Holds the g_utils_global lock */
1864
1865   static gboolean beenhere = FALSE;
1866   typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1867   static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1868   HMODULE hmodule = NULL;
1869
1870   if (!address)
1871     return NULL;
1872
1873   if (!beenhere)
1874     {
1875       p_GetModuleHandleExA =
1876         (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1877                                                "GetModuleHandleExA");
1878       beenhere = TRUE;
1879     }
1880
1881   if (p_GetModuleHandleExA == NULL ||
1882       !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1883                                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1884                                 address, &hmodule))
1885     {
1886       MEMORY_BASIC_INFORMATION mbi;
1887       VirtualQuery (address, &mbi, sizeof (mbi));
1888       hmodule = (HMODULE) mbi.AllocationBase;
1889     }
1890
1891   return hmodule;
1892 }
1893
1894 static gchar *
1895 get_module_share_dir (gconstpointer address)
1896 {
1897   HMODULE hmodule;
1898   gchar *filename;
1899   gchar *retval;
1900
1901   hmodule = get_module_for_address (address);
1902   if (hmodule == NULL)
1903     return NULL;
1904
1905   filename = g_win32_get_package_installation_directory_of_module (hmodule);
1906   retval = g_build_filename (filename, "share", NULL);
1907   g_free (filename);
1908
1909   return retval;
1910 }
1911
1912 static const gchar * const *
1913 g_win32_get_system_data_dirs_for_module_real (void (*address_of_function)(void))
1914 {
1915   GArray *data_dirs;
1916   HMODULE hmodule;
1917   static GHashTable *per_module_data_dirs = NULL;
1918   gchar **retval;
1919   gchar *p;
1920   gchar *exe_root;
1921
1922   hmodule = NULL;
1923   if (address_of_function)
1924     {
1925       G_LOCK (g_utils_global);
1926       hmodule = get_module_for_address (address_of_function);
1927       if (hmodule != NULL)
1928         {
1929           if (per_module_data_dirs == NULL)
1930             per_module_data_dirs = g_hash_table_new (NULL, NULL);
1931           else
1932             {
1933               retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1934               
1935               if (retval != NULL)
1936                 {
1937                   G_UNLOCK (g_utils_global);
1938                   return (const gchar * const *) retval;
1939                 }
1940             }
1941         }
1942     }
1943
1944   data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1945
1946   /* Documents and Settings\All Users\Application Data */
1947   p = get_special_folder (CSIDL_COMMON_APPDATA);
1948   if (p)
1949     g_array_append_val (data_dirs, p);
1950   
1951   /* Documents and Settings\All Users\Documents */
1952   p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1953   if (p)
1954     g_array_append_val (data_dirs, p);
1955         
1956   /* Using the above subfolders of Documents and Settings perhaps
1957    * makes sense from a Windows perspective.
1958    *
1959    * But looking at the actual use cases of this function in GTK+
1960    * and GNOME software, what we really want is the "share"
1961    * subdirectory of the installation directory for the package
1962    * our caller is a part of.
1963    *
1964    * The address_of_function parameter, if non-NULL, points to a
1965    * function in the calling module. Use that to determine that
1966    * module's installation folder, and use its "share" subfolder.
1967    *
1968    * Additionally, also use the "share" subfolder of the installation
1969    * locations of GLib and the .exe file being run.
1970    *
1971    * To guard against none of the above being what is really wanted,
1972    * callers of this function should have Win32-specific code to look
1973    * up their installation folder themselves, and handle a subfolder
1974    * "share" of it in the same way as the folders returned from this
1975    * function.
1976    */
1977
1978   p = get_module_share_dir (address_of_function);
1979   if (p)
1980     g_array_append_val (data_dirs, p);
1981     
1982   if (glib_dll != NULL)
1983     {
1984       gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1985       p = g_build_filename (glib_root, "share", NULL);
1986       if (p)
1987         g_array_append_val (data_dirs, p);
1988       g_free (glib_root);
1989     }
1990   
1991   exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1992   p = g_build_filename (exe_root, "share", NULL);
1993   if (p)
1994     g_array_append_val (data_dirs, p);
1995   g_free (exe_root);
1996
1997   retval = (gchar **) g_array_free (data_dirs, FALSE);
1998
1999   if (address_of_function)
2000     {
2001       if (hmodule != NULL)
2002         g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2003       G_UNLOCK (g_utils_global);
2004     }
2005
2006   return (const gchar * const *) retval;
2007 }
2008
2009 const gchar * const *
2010 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
2011 {
2012   gboolean should_call_g_get_system_data_dirs;
2013
2014   should_call_g_get_system_data_dirs = TRUE;
2015   /* These checks are the same as the ones that g_build_system_data_dirs() does.
2016    * Please keep them in sync.
2017    */
2018   G_LOCK (g_utils_global);
2019
2020   if (!g_system_data_dirs)
2021     {
2022       const gchar *data_dirs = g_getenv ("XDG_DATA_DIRS");
2023
2024       if (!data_dirs || !data_dirs[0])
2025         should_call_g_get_system_data_dirs = FALSE;
2026     }
2027
2028   G_UNLOCK (g_utils_global);
2029
2030   /* There is a subtle difference between g_win32_get_system_data_dirs_for_module (NULL),
2031    * which is what GLib code can normally call,
2032    * and g_win32_get_system_data_dirs_for_module (&_g_win32_get_system_data_dirs),
2033    * which is what the inline function used by non-GLib code calls.
2034    * The former gets prefix relative to currently-running executable,
2035    * the latter - relative to the module that calls _g_win32_get_system_data_dirs()
2036    * (disguised as g_get_system_data_dirs()), which could be an executable or
2037    * a DLL that is located somewhere else.
2038    * This is why that inline function in gutils.h exists, and why we can't just
2039    * call g_get_system_data_dirs() from there - because we need to get the address
2040    * local to the non-GLib caller-module.
2041    */
2042
2043   /*
2044    * g_get_system_data_dirs() will fall back to calling
2045    * g_win32_get_system_data_dirs_for_module_real(NULL) if XDG_DATA_DIRS is NULL
2046    * or an empty string. The checks above ensure that we do not call it in such
2047    * cases and use the address_of_function that we've been given by the inline function.
2048    * The reason we're calling g_get_system_data_dirs /at all/ is to give
2049    * XDG_DATA_DIRS precedence (if it is set).
2050    */
2051   if (should_call_g_get_system_data_dirs)
2052     return g_get_system_data_dirs ();
2053
2054   return g_win32_get_system_data_dirs_for_module_real (address_of_function);
2055 }
2056
2057 #endif
2058
2059 static gchar **
2060 g_build_system_data_dirs (void)
2061 {
2062   gchar **data_dir_vector = NULL;
2063   gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2064
2065   /* These checks are the same as the ones that g_win32_get_system_data_dirs_for_module()
2066    * does. Please keep them in sync.
2067    */
2068 #ifndef G_OS_WIN32
2069   if (!data_dirs || !data_dirs[0])
2070     data_dirs = "/usr/local/share/:/usr/share/";
2071
2072   data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2073 #else
2074   if (!data_dirs || !data_dirs[0])
2075     data_dir_vector = g_strdupv ((gchar **) g_win32_get_system_data_dirs_for_module_real (NULL));
2076   else
2077     data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2078 #endif
2079
2080   return g_steal_pointer (&data_dir_vector);
2081 }
2082
2083 /**
2084  * g_get_system_data_dirs:
2085  * 
2086  * Returns an ordered list of base directories in which to access 
2087  * system-wide application data.
2088  *
2089  * On UNIX platforms this is determined using the mechanisms described
2090  * in the
2091  * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec)
2092  * In this case the list of directories retrieved will be `XDG_DATA_DIRS`.
2093  *
2094  * On Windows it follows XDG Base Directory Specification if `XDG_DATA_DIRS` is defined.
2095  * If `XDG_DATA_DIRS` is undefined,
2096  * the first elements in the list are the Application Data
2097  * and Documents folders for All Users. (These can be determined only
2098  * on Windows 2000 or later and are not present in the list on other
2099  * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2100  * CSIDL_COMMON_DOCUMENTS.
2101  *
2102  * Then follows the "share" subfolder in the installation folder for
2103  * the package containing the DLL that calls this function, if it can
2104  * be determined.
2105  * 
2106  * Finally the list contains the "share" subfolder in the installation
2107  * folder for GLib, and in the installation folder for the package the
2108  * application's .exe file belongs to.
2109  *
2110  * The installation folders above are determined by looking up the
2111  * folder where the module (DLL or EXE) in question is located. If the
2112  * folder's name is "bin", its parent is used, otherwise the folder
2113  * itself.
2114  *
2115  * Note that on Windows the returned list can vary depending on where
2116  * this function is called.
2117  *
2118  * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
2119  *     a %NULL-terminated array of strings owned by GLib that must not be
2120  *     modified or freed.
2121  * 
2122  * Since: 2.6
2123  **/
2124 const gchar * const * 
2125 g_get_system_data_dirs (void)
2126 {
2127   const gchar * const *system_data_dirs;
2128
2129   G_LOCK (g_utils_global);
2130
2131   if (g_system_data_dirs == NULL)
2132     g_system_data_dirs = g_build_system_data_dirs ();
2133   system_data_dirs = (const gchar * const *) g_system_data_dirs;
2134
2135   G_UNLOCK (g_utils_global);
2136
2137   return system_data_dirs;
2138 }
2139
2140 static gchar **
2141 g_build_system_config_dirs (void)
2142 {
2143   gchar **conf_dir_vector = NULL;
2144   const gchar *conf_dirs = g_getenv ("XDG_CONFIG_DIRS");
2145 #ifdef G_OS_WIN32
2146   if (conf_dirs)
2147     {
2148       conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2149     }
2150   else
2151     {
2152       gchar *special_conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2153
2154       if (special_conf_dirs)
2155         conf_dir_vector = g_strsplit (special_conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2156       else
2157         /* Return empty list */
2158         conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2159
2160       g_free (special_conf_dirs);
2161     }
2162 #else
2163   if (!conf_dirs || !conf_dirs[0])
2164     conf_dirs = "/etc/xdg";
2165
2166   conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2167 #endif
2168
2169   return g_steal_pointer (&conf_dir_vector);
2170 }
2171
2172 /**
2173  * g_get_system_config_dirs:
2174  * 
2175  * Returns an ordered list of base directories in which to access 
2176  * system-wide configuration information.
2177  *
2178  * On UNIX platforms this is determined using the mechanisms described
2179  * in the
2180  * [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2181  * In this case the list of directories retrieved will be `XDG_CONFIG_DIRS`.
2182  *
2183  * On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_DIRS` is defined.
2184  * If `XDG_CONFIG_DIRS` is undefined, the directory that contains application
2185  * data for all users is used instead. A typical path is
2186  * `C:\Documents and Settings\All Users\Application Data`.
2187  * This folder is used for application data
2188  * that is not user specific. For example, an application can store
2189  * a spell-check dictionary, a database of clip art, or a log file in the
2190  * CSIDL_COMMON_APPDATA folder. This information will not roam and is available
2191  * to anyone using the computer.
2192  *
2193  * Returns: (array zero-terminated=1) (element-type filename) (transfer none):
2194  *     a %NULL-terminated array of strings owned by GLib that must not be
2195  *     modified or freed.
2196  * 
2197  * Since: 2.6
2198  **/
2199 const gchar * const *
2200 g_get_system_config_dirs (void)
2201 {
2202   const gchar * const *system_config_dirs;
2203
2204   G_LOCK (g_utils_global);
2205
2206   if (g_system_config_dirs == NULL)
2207     g_system_config_dirs = g_build_system_config_dirs ();
2208   system_config_dirs = (const gchar * const *) g_system_config_dirs;
2209
2210   G_UNLOCK (g_utils_global);
2211
2212   return system_config_dirs;
2213 }
2214
2215 /**
2216  * g_nullify_pointer:
2217  * @nullify_location: (not nullable): the memory address of the pointer.
2218  *
2219  * Set the pointer at the specified location to %NULL.
2220  **/
2221 void
2222 g_nullify_pointer (gpointer *nullify_location)
2223 {
2224   g_return_if_fail (nullify_location != NULL);
2225
2226   *nullify_location = NULL;
2227 }
2228
2229 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2230 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2231 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2232 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2233 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2234 #define EXABYTE_FACTOR  (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2235
2236 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2237 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2238 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2239 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2240 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2241 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2242
2243 /**
2244  * g_format_size:
2245  * @size: a size in bytes
2246  *
2247  * Formats a size (for example the size of a file) into a human readable
2248  * string.  Sizes are rounded to the nearest size prefix (kB, MB, GB)
2249  * and are displayed rounded to the nearest tenth. E.g. the file size
2250  * 3292528 bytes will be converted into the string "3.2 MB". The returned string
2251  * is UTF-8, and may use a non-breaking space to separate the number and units,
2252  * to ensure they aren’t separated when line wrapped.
2253  *
2254  * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2255  *
2256  * This string should be freed with g_free() when not needed any longer.
2257  *
2258  * See g_format_size_full() for more options about how the size might be
2259  * formatted.
2260  *
2261  * Returns: a newly-allocated formatted string containing a human readable
2262  *     file size
2263  *
2264  * Since: 2.30
2265  */
2266 gchar *
2267 g_format_size (guint64 size)
2268 {
2269   return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2270 }
2271
2272 /**
2273  * GFormatSizeFlags:
2274  * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2275  * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2276  *     of the returned string.  For example, "45.6 kB (45,612 bytes)".
2277  * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2278  *     suffixes. IEC units should only be used for reporting things with
2279  *     a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2280  *     Network and storage sizes should be reported in the normal SI units.
2281  * @G_FORMAT_SIZE_BITS: set the size as a quantity in bits, rather than
2282  *     bytes, and return units in bits. For example, â€˜Mb’ rather than â€˜MB’.
2283  *
2284  * Flags to modify the format of the string returned by g_format_size_full().
2285  */
2286
2287 #pragma GCC diagnostic push
2288 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2289
2290 /**
2291  * g_format_size_full:
2292  * @size: a size in bytes
2293  * @flags: #GFormatSizeFlags to modify the output
2294  *
2295  * Formats a size.
2296  *
2297  * This function is similar to g_format_size() but allows for flags
2298  * that modify the output. See #GFormatSizeFlags.
2299  *
2300  * Returns: a newly-allocated formatted string containing a human
2301  *     readable file size
2302  *
2303  * Since: 2.30
2304  */
2305 gchar *
2306 g_format_size_full (guint64          size,
2307                     GFormatSizeFlags flags)
2308 {
2309   struct Format
2310   {
2311     guint64 factor;
2312     char string[10];
2313   };
2314
2315   typedef enum
2316   {
2317     FORMAT_BYTES,
2318     FORMAT_BYTES_IEC,
2319     FORMAT_BITS,
2320     FORMAT_BITS_IEC
2321   } FormatIndex;
2322
2323   const struct Format formats[4][6] = {
2324     {
2325       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2326       { KILOBYTE_FACTOR, N_("%.1f kB") },
2327       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2328       { MEGABYTE_FACTOR, N_("%.1f MB") },
2329       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2330       { GIGABYTE_FACTOR, N_("%.1f GB") },
2331       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2332       { TERABYTE_FACTOR, N_("%.1f TB") },
2333       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2334       { PETABYTE_FACTOR, N_("%.1f PB") },
2335       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2336       { EXABYTE_FACTOR,  N_("%.1f EB") }
2337     },
2338     {
2339       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2340       { KIBIBYTE_FACTOR, N_("%.1f KiB") },
2341       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2342       { MEBIBYTE_FACTOR, N_("%.1f MiB") },
2343       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2344       { GIBIBYTE_FACTOR, N_("%.1f GiB") },
2345       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2346       { TEBIBYTE_FACTOR, N_("%.1f TiB") },
2347       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2348       { PEBIBYTE_FACTOR, N_("%.1f PiB") },
2349       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2350       { EXBIBYTE_FACTOR, N_("%.1f EiB") }
2351     },
2352     {
2353       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2354       { KILOBYTE_FACTOR, N_("%.1f kb") },
2355       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2356       { MEGABYTE_FACTOR, N_("%.1f Mb") },
2357       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2358       { GIGABYTE_FACTOR, N_("%.1f Gb") },
2359       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2360       { TERABYTE_FACTOR, N_("%.1f Tb") },
2361       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2362       { PETABYTE_FACTOR, N_("%.1f Pb") },
2363       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2364       { EXABYTE_FACTOR,  N_("%.1f Eb") }
2365     },
2366     {
2367       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2368       { KIBIBYTE_FACTOR, N_("%.1f Kib") },
2369       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2370       { MEBIBYTE_FACTOR, N_("%.1f Mib") },
2371       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2372       { GIBIBYTE_FACTOR, N_("%.1f Gib") },
2373       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2374       { TEBIBYTE_FACTOR, N_("%.1f Tib") },
2375       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2376       { PEBIBYTE_FACTOR, N_("%.1f Pib") },
2377       /* Translators: Keep the no-break space between %.1f and the unit symbol */
2378       { EXBIBYTE_FACTOR, N_("%.1f Eib") }
2379     }
2380   };
2381
2382   GString *string;
2383   FormatIndex index;
2384
2385   string = g_string_new (NULL);
2386
2387   switch (flags & ~G_FORMAT_SIZE_LONG_FORMAT)
2388     {
2389     case G_FORMAT_SIZE_DEFAULT:
2390       index = FORMAT_BYTES;
2391       break;
2392     case (G_FORMAT_SIZE_DEFAULT | G_FORMAT_SIZE_IEC_UNITS):
2393       index = FORMAT_BYTES_IEC;
2394       break;
2395     case G_FORMAT_SIZE_BITS:
2396       index = FORMAT_BITS;
2397       break;
2398     case (G_FORMAT_SIZE_BITS | G_FORMAT_SIZE_IEC_UNITS):
2399       index = FORMAT_BITS_IEC;
2400       break;
2401     default:
2402       g_assert_not_reached ();
2403     }
2404
2405
2406   if (size < formats[index][0].factor)
2407     {
2408       const char * format;
2409
2410       if (index == FORMAT_BYTES || index == FORMAT_BYTES_IEC)
2411         {
2412           format = g_dngettext (GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size);
2413         }
2414       else
2415         {
2416           format = g_dngettext (GETTEXT_PACKAGE, "%u bit", "%u bits", (guint) size);
2417         }
2418
2419       g_string_printf (string, format, (guint) size);
2420
2421       flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2422     }
2423   else
2424     {
2425       const gsize n = G_N_ELEMENTS (formats[index]);
2426       gsize i;
2427
2428       /*
2429        * Point the last format (the highest unit) by default
2430        * and then then scan all formats, starting with the 2nd one
2431        * because the 1st is already managed by with the plural form
2432        */
2433       const struct Format * f = &formats[index][n - 1];
2434
2435       for (i = 1; i < n; i++)
2436         {
2437           if (size < formats[index][i].factor)
2438             {
2439               f = &formats[index][i - 1];
2440               break;
2441             }
2442         }
2443
2444       g_string_printf (string, _(f->string), (gdouble) size / (gdouble) f->factor);
2445     }
2446
2447   if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2448     {
2449       /* First problem: we need to use the number of bytes to decide on
2450        * the plural form that is used for display, but the number of
2451        * bytes potentially exceeds the size of a guint (which is what
2452        * ngettext() takes).
2453        *
2454        * From a pragmatic standpoint, it seems that all known languages
2455        * base plural forms on one or both of the following:
2456        *
2457        *   - the lowest digits of the number
2458        *
2459        *   - if the number if greater than some small value
2460        *
2461        * Here's how we fake it:  Draw an arbitrary line at one thousand.
2462        * If the number is below that, then fine.  If it is above it,
2463        * then we take the modulus of the number by one thousand (in
2464        * order to keep the lowest digits) and add one thousand to that
2465        * (in order to ensure that 1001 is not treated the same as 1).
2466        */
2467       guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2468
2469       /* Second problem: we need to translate the string "%u byte/bit" and
2470        * "%u bytes/bits" for pluralisation, but the correct number format to
2471        * use for a gsize is different depending on which architecture
2472        * we're on.
2473        *
2474        * Solution: format the number separately and use "%s bytes/bits" on
2475        * all platforms.
2476        */
2477       const gchar *translated_format;
2478       gchar *formatted_number;
2479
2480       if (index == FORMAT_BYTES || index == FORMAT_BYTES_IEC)
2481         {
2482           /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2483           translated_format = g_dngettext (GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2484         }
2485       else
2486         {
2487           /* Translators: the %s in "%s bits" will always be replaced by a number. */
2488           translated_format = g_dngettext (GETTEXT_PACKAGE, "%s bit", "%s bits", plural_form);
2489         }
2490       formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2491
2492       g_string_append (string, " (");
2493       g_string_append_printf (string, translated_format, formatted_number);
2494       g_free (formatted_number);
2495       g_string_append (string, ")");
2496     }
2497
2498   return g_string_free (string, FALSE);
2499 }
2500
2501 #pragma GCC diagnostic pop
2502
2503 /**
2504  * g_format_size_for_display:
2505  * @size: a size in bytes
2506  *
2507  * Formats a size (for example the size of a file) into a human
2508  * readable string. Sizes are rounded to the nearest size prefix
2509  * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2510  * E.g. the file size 3292528 bytes will be converted into the
2511  * string "3.1 MB".
2512  *
2513  * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2514  *
2515  * This string should be freed with g_free() when not needed any longer.
2516  *
2517  * Returns: a newly-allocated formatted string containing a human
2518  *     readable file size
2519  *
2520  * Since: 2.16
2521  *
2522  * Deprecated:2.30: This function is broken due to its use of SI
2523  *     suffixes to denote IEC units. Use g_format_size() instead.
2524  */
2525 gchar *
2526 g_format_size_for_display (goffset size)
2527 {
2528   if (size < (goffset) KIBIBYTE_FACTOR)
2529     return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2530   else
2531     {
2532       gdouble displayed_size;
2533
2534       if (size < (goffset) MEBIBYTE_FACTOR)
2535         {
2536           displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2537           /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2538            * mean 1024 bytes.  I am aware that 'KB' is not correct, but it has been preserved for reasons of
2539            * compatibility.  Users will not see this string unless a program is using this deprecated function.
2540            * Please translate as literally as possible.
2541            */
2542           return g_strdup_printf (_("%.1f KB"), displayed_size);
2543         }
2544       else if (size < (goffset) GIBIBYTE_FACTOR)
2545         {
2546           displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2547           return g_strdup_printf (_("%.1f MB"), displayed_size);
2548         }
2549       else if (size < (goffset) TEBIBYTE_FACTOR)
2550         {
2551           displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2552           return g_strdup_printf (_("%.1f GB"), displayed_size);
2553         }
2554       else if (size < (goffset) PEBIBYTE_FACTOR)
2555         {
2556           displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2557           return g_strdup_printf (_("%.1f TB"), displayed_size);
2558         }
2559       else if (size < (goffset) EXBIBYTE_FACTOR)
2560         {
2561           displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2562           return g_strdup_printf (_("%.1f PB"), displayed_size);
2563         }
2564       else
2565         {
2566           displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2567           return g_strdup_printf (_("%.1f EB"), displayed_size);
2568         }
2569     }
2570 }
2571
2572 #if defined (G_OS_WIN32) && !defined (_WIN64)
2573
2574 /* Binary compatibility versions. Not for newly compiled code. */
2575
2576 _GLIB_EXTERN const gchar *g_get_user_name_utf8        (void);
2577 _GLIB_EXTERN const gchar *g_get_real_name_utf8        (void);
2578 _GLIB_EXTERN const gchar *g_get_home_dir_utf8         (void);
2579 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8          (void);
2580 _GLIB_EXTERN gchar       *g_find_program_in_path_utf8 (const gchar *program);
2581
2582 gchar *
2583 g_find_program_in_path_utf8 (const gchar *program)
2584 {
2585   return g_find_program_in_path (program);
2586 }
2587
2588 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2589 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2590 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2591 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2592
2593 #endif
2594
2595 /* Private API:
2596  *
2597  * Returns %TRUE if the current process was executed as setuid
2598  */ 
2599 gboolean
2600 g_check_setuid (void)
2601 {
2602 #if defined(HAVE_SYS_AUXV_H) && defined(HAVE_GETAUXVAL) && defined(AT_SECURE)
2603   unsigned long value;
2604   int errsv;
2605
2606   errno = 0;
2607   value = getauxval (AT_SECURE);
2608   errsv = errno;
2609   if (errsv)
2610     g_error ("getauxval () failed: %s", g_strerror (errsv));
2611   return value;
2612 #elif defined(HAVE_ISSETUGID) && !defined(__BIONIC__)
2613   /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2614
2615   /* Android had it in older versions but the new 64 bit ABI does not
2616    * have it anymore, and some versions of the 32 bit ABI neither.
2617    * https://code.google.com/p/android-developer-preview/issues/detail?id=168
2618    */
2619   return issetugid ();
2620 #elif defined(G_OS_UNIX)
2621   uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2622   gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2623
2624   static gsize check_setuid_initialised;
2625   static gboolean is_setuid;
2626
2627   if (g_once_init_enter (&check_setuid_initialised))
2628     {
2629 #ifdef HAVE_GETRESUID
2630       /* These aren't in the header files, so we prototype them here.
2631        */
2632       int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2633       int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2634       
2635       if (getresuid (&ruid, &euid, &suid) != 0 ||
2636           getresgid (&rgid, &egid, &sgid) != 0)
2637 #endif /* HAVE_GETRESUID */
2638         {
2639           suid = ruid = getuid ();
2640           sgid = rgid = getgid ();
2641           euid = geteuid ();
2642           egid = getegid ();
2643         }
2644
2645       is_setuid = (ruid != euid || ruid != suid ||
2646                    rgid != egid || rgid != sgid);
2647
2648       g_once_init_leave (&check_setuid_initialised, 1);
2649     }
2650   return is_setuid;
2651 #else
2652   return FALSE;
2653 #endif
2654 }
2655
2656 #ifdef G_OS_WIN32
2657 /**
2658  * g_abort:
2659  *
2660  * A wrapper for the POSIX abort() function.
2661  *
2662  * On Windows it is a function that makes extra effort (including a call
2663  * to abort()) to ensure that a debugger-catchable exception is thrown
2664  * before the program terminates.
2665  *
2666  * See your C library manual for more details about abort().
2667  *
2668  * Since: 2.50
2669  */
2670 void
2671 g_abort (void)
2672 {
2673   /* One call to break the debugger */
2674   DebugBreak ();
2675   /* One call in case CRT does get saner about abort() behaviour */
2676   abort ();
2677   /* And one call to bind them all and terminate the program for sure */
2678   ExitProcess (127);
2679 }
2680 #endif