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