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