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