Fix compilation on Android with the bionic C library
[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 static  gchar   *g_host_name = NULL;
585
586 #ifdef G_OS_WIN32
587 /* System codepage versions of the above, kept at file level so that they,
588  * too, are produced only once.
589  */
590 static  gchar   *g_tmp_dir_cp = NULL;
591 static  gchar   *g_user_name_cp = NULL;
592 static  gchar   *g_real_name_cp = NULL;
593 static  gchar   *g_home_dir_cp = NULL;
594 #endif
595
596 static  gchar   *g_user_data_dir = NULL;
597 static  gchar  **g_system_data_dirs = NULL;
598 static  gchar   *g_user_cache_dir = NULL;
599 static  gchar   *g_user_config_dir = NULL;
600 static  gchar  **g_system_config_dirs = NULL;
601
602 static  gchar  **g_user_special_dirs = NULL;
603
604 /* fifteen minutes of fame for everybody */
605 #define G_USER_DIRS_EXPIRE      15 * 60
606
607 #ifdef G_OS_WIN32
608
609 static gchar *
610 get_special_folder (int csidl)
611 {
612   wchar_t path[MAX_PATH+1];
613   HRESULT hr;
614   LPITEMIDLIST pidl = NULL;
615   BOOL b;
616   gchar *retval = NULL;
617
618   hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
619   if (hr == S_OK)
620     {
621       b = SHGetPathFromIDListW (pidl, path);
622       if (b)
623         retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
624       CoTaskMemFree (pidl);
625     }
626   return retval;
627 }
628
629 static char *
630 get_windows_directory_root (void)
631 {
632   wchar_t wwindowsdir[MAX_PATH];
633
634   if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
635     {
636       /* Usually X:\Windows, but in terminal server environments
637        * might be an UNC path, AFAIK.
638        */
639       char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
640       char *p;
641
642       if (windowsdir == NULL)
643         return g_strdup ("C:\\");
644
645       p = (char *) g_path_skip_root (windowsdir);
646       if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
647         p--;
648       *p = '\0';
649       return windowsdir;
650     }
651   else
652     return g_strdup ("C:\\");
653 }
654
655 #endif
656
657 /* HOLDS: g_utils_global_lock */
658 static void
659 g_get_any_init_do (void)
660 {
661   gchar hostname[100];
662
663   g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
664
665   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
666     {
667       g_free (g_tmp_dir);
668       g_tmp_dir = g_strdup (g_getenv ("TMP"));
669     }
670
671   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
672     {
673       g_free (g_tmp_dir);
674       g_tmp_dir = g_strdup (g_getenv ("TEMP"));
675     }
676
677 #ifdef G_OS_WIN32
678   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
679     {
680       g_free (g_tmp_dir);
681       g_tmp_dir = get_windows_directory_root ();
682     }
683 #else
684  
685 #ifdef P_tmpdir
686   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
687     {
688       gsize k;
689       g_free (g_tmp_dir);
690       g_tmp_dir = g_strdup (P_tmpdir);
691       k = strlen (g_tmp_dir);
692       if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
693         g_tmp_dir[k - 1] = '\0';
694     }
695 #endif
696   
697   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
698     {
699       g_free (g_tmp_dir);
700       g_tmp_dir = g_strdup ("/tmp");
701     }
702 #endif  /* !G_OS_WIN32 */
703   
704 #ifdef G_OS_WIN32
705   /* We check $HOME first for Win32, though it is a last resort for Unix
706    * where we prefer the results of getpwuid().
707    */
708   g_home_dir = g_strdup (g_getenv ("HOME"));
709
710   /* Only believe HOME if it is an absolute path and exists */
711   if (g_home_dir)
712     {
713       if (!(g_path_is_absolute (g_home_dir) &&
714             g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
715         {
716           g_free (g_home_dir);
717           g_home_dir = NULL;
718         }
719     }
720   
721   /* In case HOME is Unix-style (it happens), convert it to
722    * Windows style.
723    */
724   if (g_home_dir)
725     {
726       gchar *p;
727       while ((p = strchr (g_home_dir, '/')) != NULL)
728         *p = '\\';
729     }
730
731   if (!g_home_dir)
732     {
733       /* USERPROFILE is probably the closest equivalent to $HOME? */
734       if (g_getenv ("USERPROFILE") != NULL)
735         g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
736     }
737
738   if (!g_home_dir)
739     g_home_dir = get_special_folder (CSIDL_PROFILE);
740   
741   if (!g_home_dir)
742     g_home_dir = get_windows_directory_root ();
743 #endif /* G_OS_WIN32 */
744   
745 #ifdef HAVE_PWD_H
746   {
747     struct passwd *pw = NULL;
748     gpointer buffer = NULL;
749     gint error;
750     gchar *logname;
751
752 #  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
753     struct passwd pwd;
754 #    ifdef _SC_GETPW_R_SIZE_MAX  
755     /* This reurns the maximum length */
756     glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
757     
758     if (bufsize < 0)
759       bufsize = 64;
760 #    else /* _SC_GETPW_R_SIZE_MAX */
761     glong bufsize = 64;
762 #    endif /* _SC_GETPW_R_SIZE_MAX */
763
764     logname = (gchar *) g_getenv ("LOGNAME");
765         
766     do
767       {
768         g_free (buffer);
769         /* we allocate 6 extra bytes to work around a bug in 
770          * Mac OS < 10.3. See #156446
771          */
772         buffer = g_malloc (bufsize + 6);
773         errno = 0;
774         
775 #    ifdef HAVE_POSIX_GETPWUID_R
776         if (logname) {
777           error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
778           if (!pw || (pw->pw_uid != getuid ())) {
779             /* LOGNAME is lying, fall back to looking up the uid */
780             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
781           }
782         } else {
783           error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
784         }
785         error = error < 0 ? errno : error;
786 #    else /* HAVE_NONPOSIX_GETPWUID_R */
787    /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
788 #      if defined(_AIX) || defined(__hpux)
789         error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
790         pw = error == 0 ? &pwd : NULL;
791 #      else /* !_AIX */
792         if (logname) {
793           pw = getpwnam_r (logname, &pwd, buffer, bufsize);
794           if (!pw || (pw->pw_uid != getuid ())) {
795             /* LOGNAME is lying, fall back to looking up the uid */
796             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
797           }
798         } else {
799           pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
800         }
801         error = pw ? 0 : errno;
802 #      endif /* !_AIX */            
803 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
804         
805         if (!pw)
806           {
807             /* we bail out prematurely if the user id can't be found
808              * (should be pretty rare case actually), or if the buffer
809              * should be sufficiently big and lookups are still not
810              * successful.
811              */
812             if (error == 0 || error == ENOENT)
813               {
814                 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
815                            (gulong) getuid ());
816                 break;
817               }
818             if (bufsize > 32 * 1024)
819               {
820                 g_warning ("getpwuid_r(): failed due to: %s.",
821                            g_strerror (error));
822                 break;
823               }
824             
825             bufsize *= 2;
826           }
827       }
828     while (!pw);
829 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
830     
831     if (!pw)
832       {
833 #ifndef __BIONIC__
834         setpwent ();
835 #endif
836         pw = getpwuid (getuid ());
837 #ifndef __BIONIC__
838         endpwent ();
839 #endif
840       }
841     if (pw)
842       {
843         g_user_name = g_strdup (pw->pw_name);
844
845 #ifndef __BIONIC__
846         if (pw->pw_gecos && *pw->pw_gecos != '\0') 
847           {
848             gchar **gecos_fields;
849             gchar **name_parts;
850
851             /* split the gecos field and substitute '&' */
852             gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
853             name_parts = g_strsplit (gecos_fields[0], "&", 0);
854             pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
855             g_real_name = g_strjoinv (pw->pw_name, name_parts);
856             g_strfreev (gecos_fields);
857             g_strfreev (name_parts);
858           }
859 #endif
860
861         if (!g_home_dir)
862           g_home_dir = g_strdup (pw->pw_dir);
863       }
864     g_free (buffer);
865   }
866   
867 #else /* !HAVE_PWD_H */
868   
869 #ifdef G_OS_WIN32
870   {
871     guint len = UNLEN+1;
872     wchar_t buffer[UNLEN+1];
873     
874     if (GetUserNameW (buffer, (LPDWORD) &len))
875       {
876         g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
877         g_real_name = g_strdup (g_user_name);
878       }
879   }
880 #endif /* G_OS_WIN32 */
881
882 #endif /* !HAVE_PWD_H */
883
884 #ifndef G_OS_WIN32
885   if (!g_home_dir)
886     g_home_dir = g_strdup (g_getenv ("HOME"));
887 #endif
888
889 #ifdef __EMX__
890   /* change '\\' in %HOME% to '/' */
891   g_strdelimit (g_home_dir, "\\",'/');
892 #endif
893   if (!g_user_name)
894     g_user_name = g_strdup ("somebody");
895   if (!g_real_name)
896     g_real_name = g_strdup ("Unknown");
897
898   {
899 #ifndef G_OS_WIN32
900     gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
901 #else
902     DWORD size = sizeof (hostname);
903     gboolean hostname_fail = (!GetComputerName (hostname, &size));
904 #endif
905     g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
906   }
907
908 #ifdef G_OS_WIN32
909   g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
910   g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
911   g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
912
913   if (!g_tmp_dir_cp)
914     g_tmp_dir_cp = g_strdup ("\\");
915   if (!g_user_name_cp)
916     g_user_name_cp = g_strdup ("somebody");
917   if (!g_real_name_cp)
918     g_real_name_cp = g_strdup ("Unknown");
919
920   /* home_dir might be NULL, unlike tmp_dir, user_name and
921    * real_name.
922    */
923   if (g_home_dir)
924     g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
925   else
926     g_home_dir_cp = NULL;
927 #endif /* G_OS_WIN32 */
928 }
929
930 static inline void
931 g_get_any_init (void)
932 {
933   if (!g_tmp_dir)
934     g_get_any_init_do ();
935 }
936
937 static inline void
938 g_get_any_init_locked (void)
939 {
940   G_LOCK (g_utils_global);
941   g_get_any_init ();
942   G_UNLOCK (g_utils_global);
943 }
944
945
946 /**
947  * g_get_user_name:
948  *
949  * Gets the user name of the current user. The encoding of the returned
950  * string is system-defined. On UNIX, it might be the preferred file name
951  * encoding, or something else, and there is no guarantee that it is even
952  * consistent on a machine. On Windows, it is always UTF-8.
953  *
954  * Returns: the user name of the current user.
955  */
956 const gchar *
957 g_get_user_name (void)
958 {
959   g_get_any_init_locked ();
960   return g_user_name;
961 }
962
963 /**
964  * g_get_real_name:
965  *
966  * Gets the real name of the user. This usually comes from the user's entry 
967  * in the <filename>passwd</filename> file. The encoding of the returned 
968  * string is system-defined. (On Windows, it is, however, always UTF-8.) 
969  * If the real user name cannot be determined, the string "Unknown" is 
970  * returned.
971  *
972  * Returns: the user's real name.
973  */
974 const gchar *
975 g_get_real_name (void)
976 {
977   g_get_any_init_locked ();
978   return g_real_name;
979 }
980
981 /**
982  * g_get_home_dir:
983  *
984  * Gets the current user's home directory as defined in the 
985  * password database.
986  *
987  * Note that in contrast to traditional UNIX tools, this function 
988  * prefers <filename>passwd</filename> entries over the <envar>HOME</envar> 
989  * environment variable. 
990  *
991  * One of the reasons for this decision is that applications in many 
992  * cases need special handling to deal with the case where 
993  * <envar>HOME</envar> is
994  * <simplelist>
995  *   <member>Not owned by the user</member>
996  *   <member>Not writeable</member>
997  *   <member>Not even readable</member>
998  * </simplelist>
999  * Since applications are in general <emphasis>not</emphasis> written 
1000  * to deal with these situations it was considered better to make 
1001  * g_get_home_dir() not pay attention to <envar>HOME</envar> and to 
1002  * return the real home directory for the user. If applications
1003  * want to pay attention to <envar>HOME</envar>, they can do:
1004  * |[
1005  *  const char *homedir = g_getenv ("HOME");
1006  *   if (!homedir)
1007  *      homedir = g_get_home_dir (<!-- -->);
1008  * ]|
1009  *
1010  * Returns: the current user's home directory
1011  */
1012 const gchar *
1013 g_get_home_dir (void)
1014 {
1015   g_get_any_init_locked ();
1016   return g_home_dir;
1017 }
1018
1019 /**
1020  * g_get_tmp_dir:
1021  *
1022  * Gets the directory to use for temporary files. This is found from 
1023  * inspecting the environment variables <envar>TMPDIR</envar>, 
1024  * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none 
1025  * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows. 
1026  * The encoding of the returned string is system-defined. On Windows, 
1027  * it is always UTF-8. The return value is never %NULL or the empty string.
1028  *
1029  * Returns: the directory to use for temporary files.
1030  */
1031 const gchar *
1032 g_get_tmp_dir (void)
1033 {
1034   g_get_any_init_locked ();
1035   return g_tmp_dir;
1036 }
1037
1038 /**
1039  * g_get_host_name:
1040  *
1041  * Return a name for the machine. 
1042  *
1043  * The returned name is not necessarily a fully-qualified domain name,
1044  * or even present in DNS or some other name service at all. It need
1045  * not even be unique on your local network or site, but usually it
1046  * is. Callers should not rely on the return value having any specific
1047  * properties like uniqueness for security purposes. Even if the name
1048  * of the machine is changed while an application is running, the
1049  * return value from this function does not change. The returned
1050  * string is owned by GLib and should not be modified or freed. If no
1051  * name can be determined, a default fixed string "localhost" is
1052  * returned.
1053  *
1054  * Returns: the host name of the machine.
1055  *
1056  * Since: 2.8
1057  */
1058 const gchar *
1059 g_get_host_name (void)
1060 {
1061   g_get_any_init_locked ();
1062   return g_host_name;
1063 }
1064
1065 G_LOCK_DEFINE_STATIC (g_prgname);
1066 static gchar *g_prgname = NULL;
1067
1068 /**
1069  * g_get_prgname:
1070  *
1071  * Gets the name of the program. This name should <emphasis>not</emphasis> 
1072  * be localized, contrast with g_get_application_name().
1073  * (If you are using GDK or GTK+ the program name is set in gdk_init(), 
1074  * which is called by gtk_init(). The program name is found by taking 
1075  * the last component of <literal>argv[0]</literal>.)
1076  *
1077  * Returns: the name of the program. The returned string belongs 
1078  * to GLib and must not be modified or freed.
1079  */
1080 gchar*
1081 g_get_prgname (void)
1082 {
1083   gchar* retval;
1084
1085   G_LOCK (g_prgname);
1086 #ifdef G_OS_WIN32
1087   if (g_prgname == NULL)
1088     {
1089       static gboolean beenhere = FALSE;
1090
1091       if (!beenhere)
1092         {
1093           gchar *utf8_buf = NULL;
1094           wchar_t buf[MAX_PATH+1];
1095
1096           beenhere = TRUE;
1097           if (GetModuleFileNameW (GetModuleHandle (NULL),
1098                                   buf, G_N_ELEMENTS (buf)) > 0)
1099             utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1100
1101           if (utf8_buf)
1102             {
1103               g_prgname = g_path_get_basename (utf8_buf);
1104               g_free (utf8_buf);
1105             }
1106         }
1107     }
1108 #endif
1109   retval = g_prgname;
1110   G_UNLOCK (g_prgname);
1111
1112   return retval;
1113 }
1114
1115 /**
1116  * g_set_prgname:
1117  * @prgname: the name of the program.
1118  *
1119  * Sets the name of the program. This name should <emphasis>not</emphasis> 
1120  * be localized, contrast with g_set_application_name(). Note that for 
1121  * thread-safety reasons this function can only be called once.
1122  */
1123 void
1124 g_set_prgname (const gchar *prgname)
1125 {
1126   G_LOCK (g_prgname);
1127   g_free (g_prgname);
1128   g_prgname = g_strdup (prgname);
1129   G_UNLOCK (g_prgname);
1130 }
1131
1132 G_LOCK_DEFINE_STATIC (g_application_name);
1133 static gchar *g_application_name = NULL;
1134
1135 /**
1136  * g_get_application_name:
1137  * 
1138  * Gets a human-readable name for the application, as set by
1139  * g_set_application_name(). This name should be localized if
1140  * possible, and is intended for display to the user.  Contrast with
1141  * g_get_prgname(), which gets a non-localized name. If
1142  * g_set_application_name() has not been called, returns the result of
1143  * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1144  * been called).
1145  * 
1146  * Return value: human-readable application name. may return %NULL
1147  *
1148  * Since: 2.2
1149  **/
1150 const gchar *
1151 g_get_application_name (void)
1152 {
1153   gchar* retval;
1154
1155   G_LOCK (g_application_name);
1156   retval = g_application_name;
1157   G_UNLOCK (g_application_name);
1158
1159   if (retval == NULL)
1160     return g_get_prgname ();
1161   
1162   return retval;
1163 }
1164
1165 /**
1166  * g_set_application_name:
1167  * @application_name: localized name of the application
1168  *
1169  * Sets a human-readable name for the application. This name should be
1170  * localized if possible, and is intended for display to the user.
1171  * Contrast with g_set_prgname(), which sets a non-localized name.
1172  * g_set_prgname() will be called automatically by gtk_init(),
1173  * but g_set_application_name() will not.
1174  *
1175  * Note that for thread safety reasons, this function can only
1176  * be called once.
1177  *
1178  * The application name will be used in contexts such as error messages,
1179  * or when displaying an application's name in the task list.
1180  * 
1181  * Since: 2.2
1182  **/
1183 void
1184 g_set_application_name (const gchar *application_name)
1185 {
1186   gboolean already_set = FALSE;
1187         
1188   G_LOCK (g_application_name);
1189   if (g_application_name)
1190     already_set = TRUE;
1191   else
1192     g_application_name = g_strdup (application_name);
1193   G_UNLOCK (g_application_name);
1194
1195   if (already_set)
1196     g_warning ("g_set_application_name() called multiple times");
1197 }
1198
1199 /**
1200  * g_get_user_data_dir:
1201  * 
1202  * Returns a base directory in which to access application data such
1203  * as icons that is customized for a particular user.  
1204  *
1205  * On UNIX platforms this is determined using the mechanisms described in
1206  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1207  * XDG Base Directory Specification</ulink>.
1208  * In this case the directory retrieved will be XDG_DATA_HOME.
1209  *
1210  * On Windows this is the folder to use for local (as opposed to
1211  * roaming) application data. See documentation for
1212  * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1213  * what g_get_user_config_dir() returns.
1214  *
1215  * Return value: a string owned by GLib that must not be modified 
1216  *               or freed.
1217  * Since: 2.6
1218  **/
1219 const gchar *
1220 g_get_user_data_dir (void)
1221 {
1222   gchar *data_dir;  
1223
1224   G_LOCK (g_utils_global);
1225
1226   if (!g_user_data_dir)
1227     {
1228 #ifdef G_OS_WIN32
1229       data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1230 #else
1231       data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1232
1233       if (data_dir && data_dir[0])
1234         data_dir = g_strdup (data_dir);
1235 #endif
1236       if (!data_dir || !data_dir[0])
1237         {
1238           g_get_any_init ();
1239
1240           if (g_home_dir)
1241             data_dir = g_build_filename (g_home_dir, ".local", 
1242                                          "share", NULL);
1243           else
1244             data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local", 
1245                                          "share", NULL);
1246         }
1247
1248       g_user_data_dir = data_dir;
1249     }
1250   else
1251     data_dir = g_user_data_dir;
1252
1253   G_UNLOCK (g_utils_global);
1254
1255   return data_dir;
1256 }
1257
1258 static void
1259 g_init_user_config_dir (void)
1260 {
1261   gchar *config_dir;
1262
1263   if (!g_user_config_dir)
1264     {
1265 #ifdef G_OS_WIN32
1266       config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1267 #else
1268       config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1269
1270       if (config_dir && config_dir[0])
1271         config_dir = g_strdup (config_dir);
1272 #endif
1273       if (!config_dir || !config_dir[0])
1274         {
1275           g_get_any_init ();
1276
1277           if (g_home_dir)
1278             config_dir = g_build_filename (g_home_dir, ".config", NULL);
1279           else
1280             config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
1281         }
1282
1283       g_user_config_dir = config_dir;
1284     }
1285 }
1286
1287 /**
1288  * g_get_user_config_dir:
1289  * 
1290  * Returns a base directory in which to store user-specific application 
1291  * configuration information such as user preferences and settings. 
1292  *
1293  * On UNIX platforms this is determined using the mechanisms described in
1294  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1295  * XDG Base Directory Specification</ulink>.
1296  * In this case the directory retrieved will be XDG_CONFIG_HOME.
1297  *
1298  * On Windows this is the folder to use for local (as opposed to
1299  * roaming) application data. See documentation for
1300  * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1301  * what g_get_user_data_dir() returns.
1302  *
1303  * Return value: a string owned by GLib that must not be modified 
1304  *               or freed.
1305  * Since: 2.6
1306  **/
1307 const gchar *
1308 g_get_user_config_dir (void)
1309 {
1310   G_LOCK (g_utils_global);
1311
1312   g_init_user_config_dir ();
1313
1314   G_UNLOCK (g_utils_global);
1315
1316   return g_user_config_dir;
1317 }
1318
1319 /**
1320  * g_get_user_cache_dir:
1321  * 
1322  * Returns a base directory in which to store non-essential, cached
1323  * data specific to particular user.
1324  *
1325  * On UNIX platforms this is determined using the mechanisms described in
1326  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1327  * XDG Base Directory Specification</ulink>.
1328  * In this case the directory retrieved will be XDG_CACHE_HOME.
1329  *
1330  * On Windows is the directory that serves as a common repository for
1331  * temporary Internet files. A typical path is
1332  * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1333  * See documentation for CSIDL_INTERNET_CACHE.
1334  *
1335  * Return value: a string owned by GLib that must not be modified 
1336  *               or freed.
1337  * Since: 2.6
1338  **/
1339 const gchar *
1340 g_get_user_cache_dir (void)
1341 {
1342   gchar *cache_dir;  
1343
1344   G_LOCK (g_utils_global);
1345
1346   if (!g_user_cache_dir)
1347     {
1348 #ifdef G_OS_WIN32
1349       cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1350 #else
1351       cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1352
1353       if (cache_dir && cache_dir[0])
1354           cache_dir = g_strdup (cache_dir);
1355 #endif
1356       if (!cache_dir || !cache_dir[0])
1357         {
1358           g_get_any_init ();
1359         
1360           if (g_home_dir)
1361             cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
1362           else
1363             cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
1364         }
1365       g_user_cache_dir = cache_dir;
1366     }
1367   else
1368     cache_dir = g_user_cache_dir;
1369
1370   G_UNLOCK (g_utils_global);
1371
1372   return cache_dir;
1373 }
1374
1375 /**
1376  * g_get_user_runtime_dir:
1377  *
1378  * Returns a directory that is unique to the current user on the local
1379  * system.
1380  *
1381  * On UNIX platforms this is determined using the mechanisms described in
1382  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1383  * XDG Base Directory Specification</ulink>.  This is the directory
1384  * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
1385  * In the case that this variable is not set, GLib will issue a warning
1386  * message to stderr and return the value of g_get_user_cache_dir().
1387  *
1388  * On Windows this is the folder to use for local (as opposed to
1389  * roaming) application data. See documentation for
1390  * CSIDL_LOCAL_APPDATA.  Note that on Windows it thus is the same as
1391  * what g_get_user_config_dir() returns.
1392  *
1393  * Returns: a string owned by GLib that must not be modified or freed.
1394  *
1395  * Since: 2.28
1396  **/
1397 const gchar *
1398 g_get_user_runtime_dir (void)
1399 {
1400 #ifndef G_OS_WIN32
1401   static const gchar *runtime_dir;
1402   static gsize initialised;
1403
1404   if (g_once_init_enter (&initialised))
1405     {
1406       runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1407       
1408       g_once_init_leave (&initialised, 1);
1409     }
1410
1411   if (runtime_dir)
1412     return runtime_dir;
1413
1414   /* Both fallback for UNIX and the default
1415    * in Windows: use the user cache directory.
1416    */
1417 #endif
1418
1419   return g_get_user_cache_dir ();
1420 }
1421
1422 #ifdef HAVE_CARBON
1423
1424 static gchar *
1425 find_folder (OSType type)
1426 {
1427   gchar *filename = NULL;
1428   FSRef  found;
1429
1430   if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1431     {
1432       CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1433
1434       if (url)
1435         {
1436           CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1437
1438           if (path)
1439             {
1440               filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1441
1442               if (! filename)
1443                 {
1444                   filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1445
1446                   CFStringGetCString (path, filename,
1447                                       CFStringGetLength (path) * 3 + 1,
1448                                       kCFStringEncodingUTF8);
1449                 }
1450
1451               CFRelease (path);
1452             }
1453
1454           CFRelease (url);
1455         }
1456     }
1457
1458   return filename;
1459 }
1460
1461 static void
1462 load_user_special_dirs (void)
1463 {
1464   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1465   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1466   g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1467   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1468   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1469   g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1470   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1471   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1472 }
1473
1474 #endif /* HAVE_CARBON */
1475
1476 #if defined(G_OS_WIN32)
1477 static void
1478 load_user_special_dirs (void)
1479 {
1480   typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1481                                                     DWORD dwFlags,
1482                                                     HANDLE hToken,
1483                                                     PWSTR *ppszPath);
1484   t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1485
1486   static const GUID FOLDERID_Downloads =
1487     { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1488   static const GUID FOLDERID_Public =
1489     { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1490
1491   wchar_t *wcp;
1492
1493   p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1494                                                                     "SHGetKnownFolderPath");
1495
1496   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1497   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1498
1499   if (p_SHGetKnownFolderPath == NULL)
1500     {
1501       g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1502     }
1503   else
1504     {
1505       wcp = NULL;
1506       (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1507       if (wcp)
1508         {
1509           g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1510           if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1511               g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1512           CoTaskMemFree (wcp);
1513         }
1514       else
1515           g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1516     }
1517
1518   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1519   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1520
1521   if (p_SHGetKnownFolderPath == NULL)
1522     {
1523       /* XXX */
1524       g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1525     }
1526   else
1527     {
1528       wcp = NULL;
1529       (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1530       if (wcp)
1531         {
1532           g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1533           if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1534               g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1535           CoTaskMemFree (wcp);
1536         }
1537       else
1538           g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1539     }
1540   
1541   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1542   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1543 }
1544 #endif /* G_OS_WIN32 */
1545
1546 static void g_init_user_config_dir (void);
1547
1548 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
1549
1550 /* adapted from xdg-user-dir-lookup.c
1551  *
1552  * Copyright (C) 2007 Red Hat Inc.
1553  *
1554  * Permission is hereby granted, free of charge, to any person
1555  * obtaining a copy of this software and associated documentation files
1556  * (the "Software"), to deal in the Software without restriction,
1557  * including without limitation the rights to use, copy, modify, merge,
1558  * publish, distribute, sublicense, and/or sell copies of the Software,
1559  * and to permit persons to whom the Software is furnished to do so,
1560  * subject to the following conditions: 
1561  *
1562  * The above copyright notice and this permission notice shall be
1563  * included in all copies or substantial portions of the Software. 
1564  *
1565  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1566  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1567  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1568  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1569  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1570  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1571  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1572  * SOFTWARE.
1573  */
1574 static void
1575 load_user_special_dirs (void)
1576 {
1577   gchar *config_file;
1578   gchar *data;
1579   gchar **lines;
1580   gint n_lines, i;
1581   
1582   g_init_user_config_dir ();
1583   config_file = g_build_filename (g_user_config_dir,
1584                                   "user-dirs.dirs",
1585                                   NULL);
1586   
1587   if (!g_file_get_contents (config_file, &data, NULL, NULL))
1588     {
1589       g_free (config_file);
1590       return;
1591     }
1592
1593   lines = g_strsplit (data, "\n", -1);
1594   n_lines = g_strv_length (lines);
1595   g_free (data);
1596   
1597   for (i = 0; i < n_lines; i++)
1598     {
1599       gchar *buffer = lines[i];
1600       gchar *d, *p;
1601       gint len;
1602       gboolean is_relative = FALSE;
1603       GUserDirectory directory;
1604
1605       /* Remove newline at end */
1606       len = strlen (buffer);
1607       if (len > 0 && buffer[len - 1] == '\n')
1608         buffer[len - 1] = 0;
1609       
1610       p = buffer;
1611       while (*p == ' ' || *p == '\t')
1612         p++;
1613       
1614       if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1615         {
1616           directory = G_USER_DIRECTORY_DESKTOP;
1617           p += strlen ("XDG_DESKTOP_DIR");
1618         }
1619       else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1620         {
1621           directory = G_USER_DIRECTORY_DOCUMENTS;
1622           p += strlen ("XDG_DOCUMENTS_DIR");
1623         }
1624       else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1625         {
1626           directory = G_USER_DIRECTORY_DOWNLOAD;
1627           p += strlen ("XDG_DOWNLOAD_DIR");
1628         }
1629       else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1630         {
1631           directory = G_USER_DIRECTORY_MUSIC;
1632           p += strlen ("XDG_MUSIC_DIR");
1633         }
1634       else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1635         {
1636           directory = G_USER_DIRECTORY_PICTURES;
1637           p += strlen ("XDG_PICTURES_DIR");
1638         }
1639       else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1640         {
1641           directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1642           p += strlen ("XDG_PUBLICSHARE_DIR");
1643         }
1644       else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1645         {
1646           directory = G_USER_DIRECTORY_TEMPLATES;
1647           p += strlen ("XDG_TEMPLATES_DIR");
1648         }
1649       else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1650         {
1651           directory = G_USER_DIRECTORY_VIDEOS;
1652           p += strlen ("XDG_VIDEOS_DIR");
1653         }
1654       else
1655         continue;
1656
1657       while (*p == ' ' || *p == '\t')
1658         p++;
1659
1660       if (*p != '=')
1661         continue;
1662       p++;
1663
1664       while (*p == ' ' || *p == '\t')
1665         p++;
1666
1667       if (*p != '"')
1668         continue;
1669       p++;
1670
1671       if (strncmp (p, "$HOME", 5) == 0)
1672         {
1673           p += 5;
1674           is_relative = TRUE;
1675         }
1676       else if (*p != '/')
1677         continue;
1678
1679       d = strrchr (p, '"');
1680       if (!d)
1681         continue;
1682       *d = 0;
1683
1684       d = p;
1685       
1686       /* remove trailing slashes */
1687       len = strlen (d);
1688       if (d[len - 1] == '/')
1689         d[len - 1] = 0;
1690       
1691       if (is_relative)
1692         {
1693           g_get_any_init ();
1694           g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
1695         }
1696       else
1697         g_user_special_dirs[directory] = g_strdup (d);
1698     }
1699
1700   g_strfreev (lines);
1701   g_free (config_file);
1702 }
1703
1704 #endif /* G_OS_UNIX && !HAVE_CARBON */
1705
1706
1707 /**
1708  * g_reload_user_special_dirs_cache:
1709  *
1710  * Resets the cache used for g_get_user_special_dir(), so
1711  * that the latest on-disk version is used. Call this only
1712  * if you just changed the data on disk yourself.
1713  *
1714  * Due to threadsafety issues this may cause leaking of strings
1715  * that were previously returned from g_get_user_special_dir()
1716  * that can't be freed. We ensure to only leak the data for
1717  * the directories that actually changed value though.
1718  *
1719  * Since: 2.22
1720  */
1721 void
1722 g_reload_user_special_dirs_cache (void)
1723 {
1724   int i;
1725
1726   G_LOCK (g_utils_global);
1727
1728   if (g_user_special_dirs != NULL)
1729     {
1730       /* save a copy of the pointer, to check if some memory can be preserved */
1731       char **old_g_user_special_dirs = g_user_special_dirs;
1732       char *old_val;
1733
1734       /* recreate and reload our cache */
1735       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1736       load_user_special_dirs ();
1737
1738       /* only leak changed directories */
1739       for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1740         {
1741           old_val = old_g_user_special_dirs[i];
1742           if (g_user_special_dirs[i] == NULL)
1743             {
1744               g_user_special_dirs[i] = old_val;
1745             }
1746           else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1747             {
1748               /* don't leak */
1749               g_free (g_user_special_dirs[i]);
1750               g_user_special_dirs[i] = old_val;
1751             }
1752           else
1753             g_free (old_val);
1754         }
1755
1756       /* free the old array */
1757       g_free (old_g_user_special_dirs);
1758     }
1759
1760   G_UNLOCK (g_utils_global);
1761 }
1762
1763 /**
1764  * g_get_user_special_dir:
1765  * @directory: the logical id of special directory
1766  *
1767  * Returns the full path of a special directory using its logical id.
1768  *
1769  * On Unix this is done using the XDG special user directories.
1770  * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1771  * falls back to <filename>$HOME/Desktop</filename> when XDG special
1772  * user directories have not been set up. 
1773  *
1774  * Depending on the platform, the user might be able to change the path
1775  * of the special directory without requiring the session to restart; GLib
1776  * will not reflect any change once the special directories are loaded.
1777  *
1778  * Return value: the path to the specified special directory, or %NULL
1779  *   if the logical id was not found. The returned string is owned by
1780  *   GLib and should not be modified or freed.
1781  *
1782  * Since: 2.14
1783  */
1784 const gchar *
1785 g_get_user_special_dir (GUserDirectory directory)
1786 {
1787   g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1788                         directory < G_USER_N_DIRECTORIES, NULL);
1789
1790   G_LOCK (g_utils_global);
1791
1792   if (G_UNLIKELY (g_user_special_dirs == NULL))
1793     {
1794       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1795
1796       load_user_special_dirs ();
1797
1798       /* Special-case desktop for historical compatibility */
1799       if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1800         {
1801           g_get_any_init ();
1802
1803           g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
1804             g_build_filename (g_home_dir, "Desktop", NULL);
1805         }
1806     }
1807
1808   G_UNLOCK (g_utils_global);
1809
1810   return g_user_special_dirs[directory];
1811 }
1812
1813 #ifdef G_OS_WIN32
1814
1815 #undef g_get_system_data_dirs
1816
1817 static HMODULE
1818 get_module_for_address (gconstpointer address)
1819 {
1820   /* Holds the g_utils_global lock */
1821
1822   static gboolean beenhere = FALSE;
1823   typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1824   static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1825   HMODULE hmodule = NULL;
1826
1827   if (!address)
1828     return NULL;
1829
1830   if (!beenhere)
1831     {
1832       p_GetModuleHandleExA =
1833         (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1834                                                "GetModuleHandleExA");
1835       beenhere = TRUE;
1836     }
1837
1838   if (p_GetModuleHandleExA == NULL ||
1839       !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1840                                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1841                                 address, &hmodule))
1842     {
1843       MEMORY_BASIC_INFORMATION mbi;
1844       VirtualQuery (address, &mbi, sizeof (mbi));
1845       hmodule = (HMODULE) mbi.AllocationBase;
1846     }
1847
1848   return hmodule;
1849 }
1850
1851 static gchar *
1852 get_module_share_dir (gconstpointer address)
1853 {
1854   HMODULE hmodule;
1855   gchar *filename;
1856   gchar *retval;
1857
1858   hmodule = get_module_for_address (address);
1859   if (hmodule == NULL)
1860     return NULL;
1861
1862   filename = g_win32_get_package_installation_directory_of_module (hmodule);
1863   retval = g_build_filename (filename, "share", NULL);
1864   g_free (filename);
1865
1866   return retval;
1867 }
1868
1869 const gchar * const *
1870 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
1871 {
1872   GArray *data_dirs;
1873   HMODULE hmodule;
1874   static GHashTable *per_module_data_dirs = NULL;
1875   gchar **retval;
1876   gchar *p;
1877   gchar *exe_root;
1878       
1879   if (address_of_function)
1880     {
1881       G_LOCK (g_utils_global);
1882       hmodule = get_module_for_address (address_of_function);
1883       if (hmodule != NULL)
1884         {
1885           if (per_module_data_dirs == NULL)
1886             per_module_data_dirs = g_hash_table_new (NULL, NULL);
1887           else
1888             {
1889               retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1890               
1891               if (retval != NULL)
1892                 {
1893                   G_UNLOCK (g_utils_global);
1894                   return (const gchar * const *) retval;
1895                 }
1896             }
1897         }
1898     }
1899
1900   data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1901
1902   /* Documents and Settings\All Users\Application Data */
1903   p = get_special_folder (CSIDL_COMMON_APPDATA);
1904   if (p)
1905     g_array_append_val (data_dirs, p);
1906   
1907   /* Documents and Settings\All Users\Documents */
1908   p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1909   if (p)
1910     g_array_append_val (data_dirs, p);
1911         
1912   /* Using the above subfolders of Documents and Settings perhaps
1913    * makes sense from a Windows perspective.
1914    *
1915    * But looking at the actual use cases of this function in GTK+
1916    * and GNOME software, what we really want is the "share"
1917    * subdirectory of the installation directory for the package
1918    * our caller is a part of.
1919    *
1920    * The address_of_function parameter, if non-NULL, points to a
1921    * function in the calling module. Use that to determine that
1922    * module's installation folder, and use its "share" subfolder.
1923    *
1924    * Additionally, also use the "share" subfolder of the installation
1925    * locations of GLib and the .exe file being run.
1926    *
1927    * To guard against none of the above being what is really wanted,
1928    * callers of this function should have Win32-specific code to look
1929    * up their installation folder themselves, and handle a subfolder
1930    * "share" of it in the same way as the folders returned from this
1931    * function.
1932    */
1933
1934   p = get_module_share_dir (address_of_function);
1935   if (p)
1936     g_array_append_val (data_dirs, p);
1937     
1938   if (glib_dll != NULL)
1939     {
1940       gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1941       p = g_build_filename (glib_root, "share", NULL);
1942       if (p)
1943         g_array_append_val (data_dirs, p);
1944       g_free (glib_root);
1945     }
1946   
1947   exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1948   p = g_build_filename (exe_root, "share", NULL);
1949   if (p)
1950     g_array_append_val (data_dirs, p);
1951   g_free (exe_root);
1952
1953   retval = (gchar **) g_array_free (data_dirs, FALSE);
1954
1955   if (address_of_function)
1956     {
1957       if (hmodule != NULL)
1958         g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1959       G_UNLOCK (g_utils_global);
1960     }
1961
1962   return (const gchar * const *) retval;
1963 }
1964
1965 #endif
1966
1967 /**
1968  * g_get_system_data_dirs:
1969  * 
1970  * Returns an ordered list of base directories in which to access 
1971  * system-wide application data.
1972  *
1973  * On UNIX platforms this is determined using the mechanisms described in
1974  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1975  * XDG Base Directory Specification</ulink>
1976  * In this case the list of directories retrieved will be XDG_DATA_DIRS.
1977  *
1978  * On Windows the first elements in the list are the Application Data
1979  * and Documents folders for All Users. (These can be determined only
1980  * on Windows 2000 or later and are not present in the list on other
1981  * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1982  * CSIDL_COMMON_DOCUMENTS.
1983  *
1984  * Then follows the "share" subfolder in the installation folder for
1985  * the package containing the DLL that calls this function, if it can
1986  * be determined.
1987  * 
1988  * Finally the list contains the "share" subfolder in the installation
1989  * folder for GLib, and in the installation folder for the package the
1990  * application's .exe file belongs to.
1991  *
1992  * The installation folders above are determined by looking up the
1993  * folder where the module (DLL or EXE) in question is located. If the
1994  * folder's name is "bin", its parent is used, otherwise the folder
1995  * itself.
1996  *
1997  * Note that on Windows the returned list can vary depending on where
1998  * this function is called.
1999  *
2000  * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must 
2001  *               not be modified or freed.
2002  * Since: 2.6
2003  **/
2004 const gchar * const * 
2005 g_get_system_data_dirs (void)
2006 {
2007   gchar **data_dir_vector;
2008
2009   G_LOCK (g_utils_global);
2010
2011   if (!g_system_data_dirs)
2012     {
2013 #ifdef G_OS_WIN32
2014       data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2015 #else
2016       gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2017
2018       if (!data_dirs || !data_dirs[0])
2019           data_dirs = "/usr/local/share/:/usr/share/";
2020
2021       data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2022 #endif
2023
2024       g_system_data_dirs = data_dir_vector;
2025     }
2026   else
2027     data_dir_vector = g_system_data_dirs;
2028
2029   G_UNLOCK (g_utils_global);
2030
2031   return (const gchar * const *) data_dir_vector;
2032 }
2033
2034 /**
2035  * g_get_system_config_dirs:
2036  * 
2037  * Returns an ordered list of base directories in which to access 
2038  * system-wide configuration information.
2039  *
2040  * On UNIX platforms this is determined using the mechanisms described in
2041  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2042  * XDG Base Directory Specification</ulink>.
2043  * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2044  *
2045  * On Windows is the directory that contains application data for all users.
2046  * A typical path is C:\Documents and Settings\All Users\Application Data.
2047  * This folder is used for application data that is not user specific.
2048  * For example, an application can store a spell-check dictionary, a database
2049  * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2050  * This information will not roam and is available to anyone using the computer.
2051  *
2052  * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must 
2053  *               not be modified or freed.
2054  * Since: 2.6
2055  **/
2056 const gchar * const *
2057 g_get_system_config_dirs (void)
2058 {
2059   gchar *conf_dirs, **conf_dir_vector;
2060
2061   G_LOCK (g_utils_global);
2062
2063   if (!g_system_config_dirs)
2064     {
2065 #ifdef G_OS_WIN32
2066       conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2067       if (conf_dirs)
2068         {
2069           conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2070           g_free (conf_dirs);
2071         }
2072       else
2073         {
2074           /* Return empty list */
2075           conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2076         }
2077 #else
2078       conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2079
2080       if (!conf_dirs || !conf_dirs[0])
2081           conf_dirs = "/etc/xdg";
2082
2083       conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2084 #endif
2085
2086       g_system_config_dirs = conf_dir_vector;
2087     }
2088   else
2089     conf_dir_vector = g_system_config_dirs;
2090   G_UNLOCK (g_utils_global);
2091
2092   return (const gchar * const *) conf_dir_vector;
2093 }
2094
2095 /**
2096  * g_nullify_pointer:
2097  * @nullify_location: the memory address of the pointer.
2098  *
2099  * Set the pointer at the specified location to %NULL.
2100  **/
2101 void
2102 g_nullify_pointer (gpointer *nullify_location)
2103 {
2104   g_return_if_fail (nullify_location != NULL);
2105
2106   *nullify_location = NULL;
2107 }
2108
2109 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2110 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2111 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2112 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2113 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2114 #define EXABYTE_FACTOR  (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2115
2116 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2117 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2118 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2119 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2120 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2121 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2122
2123 /**
2124  * g_format_size:
2125  * @size: a size in bytes
2126  *
2127  * Formats a size (for example the size of a file) into a human readable
2128  * string.  Sizes are rounded to the nearest size prefix (kB, MB, GB)
2129  * and are displayed rounded to the nearest tenth. E.g. the file size
2130  * 3292528 bytes will be converted into the string "3.2 MB".
2131  *
2132  * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2133  *
2134  * This string should be freed with g_free() when not needed any longer.
2135  *
2136  * See g_format_size_full() for more options about how the size might be
2137  * formatted.
2138  *
2139  * Returns: a newly-allocated formatted string containing a human readable
2140  *     file size
2141  *
2142  * Since: 2.30
2143  */
2144 gchar *
2145 g_format_size (guint64 size)
2146 {
2147   return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2148 }
2149
2150 /**
2151  * GFormatSizeFlags:
2152  * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2153  * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2154  *     of the returned string.  For example, "45.6 kB (45,612 bytes)".
2155  * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2156  *     suffixes. IEC units should only be used for reporting things with
2157  *     a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2158  *     Network and storage sizes should be reported in the normal SI units.
2159  *
2160  * Flags to modify the format of the string returned by g_format_size_full().
2161  */
2162
2163 /**
2164  * g_format_size_full:
2165  * @size: a size in bytes
2166  * @flags: #GFormatSizeFlags to modify the output
2167  *
2168  * Formats a size.
2169  *
2170  * This function is similar to g_format_size() but allows for flags
2171  * that modify the output. See #GFormatSizeFlags.
2172  *
2173  * Returns: a newly-allocated formatted string containing a human
2174  *     readable file size
2175  *
2176  * Since: 2.30
2177  */
2178 gchar *
2179 g_format_size_full (guint64          size,
2180                     GFormatSizeFlags flags)
2181 {
2182   GString *string;
2183
2184   string = g_string_new (NULL);
2185
2186   if (flags & G_FORMAT_SIZE_IEC_UNITS)
2187     {
2188       if (size < KIBIBYTE_FACTOR)
2189         {
2190           g_string_printf (string,
2191                            g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2192                            (guint) size);
2193           flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2194         }
2195
2196       else if (size < MEBIBYTE_FACTOR)
2197         g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2198       else if (size < GIBIBYTE_FACTOR)
2199         g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2200
2201       else if (size < TEBIBYTE_FACTOR)
2202         g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2203
2204       else if (size < PEBIBYTE_FACTOR)
2205         g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2206
2207       else if (size < EXBIBYTE_FACTOR)
2208         g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2209
2210       else
2211         g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2212     }
2213   else
2214     {
2215       if (size < KILOBYTE_FACTOR)
2216         {
2217           g_string_printf (string,
2218                            g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2219                            (guint) size);
2220           flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2221         }
2222
2223       else if (size < MEGABYTE_FACTOR)
2224         g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2225
2226       else if (size < GIGABYTE_FACTOR)
2227         g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2228
2229       else if (size < TERABYTE_FACTOR)
2230         g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2231       else if (size < PETABYTE_FACTOR)
2232         g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2233
2234       else if (size < EXABYTE_FACTOR)
2235         g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2236
2237       else
2238         g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2239     }
2240
2241   if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2242     {
2243       /* First problem: we need to use the number of bytes to decide on
2244        * the plural form that is used for display, but the number of
2245        * bytes potentially exceeds the size of a guint (which is what
2246        * ngettext() takes).
2247        *
2248        * From a pragmatic standpoint, it seems that all known languages
2249        * base plural forms on one or both of the following:
2250        *
2251        *   - the lowest digits of the number
2252        *
2253        *   - if the number if greater than some small value
2254        *
2255        * Here's how we fake it:  Draw an arbitrary line at one thousand.
2256        * If the number is below that, then fine.  If it is above it,
2257        * then we take the modulus of the number by one thousand (in
2258        * order to keep the lowest digits) and add one thousand to that
2259        * (in order to ensure that 1001 is not treated the same as 1).
2260        */
2261       guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2262
2263       /* Second problem: we need to translate the string "%u byte" and
2264        * "%u bytes" for pluralisation, but the correct number format to
2265        * use for a gsize is different depending on which architecture
2266        * we're on.
2267        *
2268        * Solution: format the number separately and use "%s bytes" on
2269        * all platforms.
2270        */
2271       const gchar *translated_format;
2272       gchar *formatted_number;
2273
2274       /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2275       translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2276       /* XXX: Windows doesn't support the "'" format modifier, so we
2277        * must not use it there.  Instead, just display the number
2278        * without separation.  Bug #655336 is open until a solution is
2279        * found.
2280        */
2281 #ifndef G_OS_WIN32
2282       formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2283 #else
2284       formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2285 #endif
2286
2287       g_string_append (string, " (");
2288       g_string_append_printf (string, translated_format, formatted_number);
2289       g_free (formatted_number);
2290       g_string_append (string, ")");
2291     }
2292
2293   return g_string_free (string, FALSE);
2294 }
2295
2296 /**
2297  * g_format_size_for_display:
2298  * @size: a size in bytes
2299  *
2300  * Formats a size (for example the size of a file) into a human
2301  * readable string. Sizes are rounded to the nearest size prefix
2302  * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2303  * E.g. the file size 3292528 bytes will be converted into the
2304  * string "3.1 MB".
2305  *
2306  * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2307  *
2308  * This string should be freed with g_free() when not needed any longer.
2309  *
2310  * Returns: a newly-allocated formatted string containing a human
2311  *     readable file size
2312  *
2313  * Since: 2.16
2314  *
2315  * Deprecated:2.30: This function is broken due to its use of SI
2316  *     suffixes to denote IEC units. Use g_format_size() instead.
2317  */
2318 gchar *
2319 g_format_size_for_display (goffset size)
2320 {
2321   if (size < (goffset) KIBIBYTE_FACTOR)
2322     return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2323   else
2324     {
2325       gdouble displayed_size;
2326
2327       if (size < (goffset) MEBIBYTE_FACTOR)
2328         {
2329           displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2330           /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2331            * mean 1024 bytes.  I am aware that 'KB' is not correct, but it has been preserved for reasons of
2332            * compatibility.  Users will not see this string unless a program is using this deprecated function.
2333            * Please translate as literally as possible.
2334            */
2335           return g_strdup_printf (_("%.1f KB"), displayed_size);
2336         }
2337       else if (size < (goffset) GIBIBYTE_FACTOR)
2338         {
2339           displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2340           return g_strdup_printf (_("%.1f MB"), displayed_size);
2341         }
2342       else if (size < (goffset) TEBIBYTE_FACTOR)
2343         {
2344           displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2345           return g_strdup_printf (_("%.1f GB"), displayed_size);
2346         }
2347       else if (size < (goffset) PEBIBYTE_FACTOR)
2348         {
2349           displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2350           return g_strdup_printf (_("%.1f TB"), displayed_size);
2351         }
2352       else if (size < (goffset) EXBIBYTE_FACTOR)
2353         {
2354           displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2355           return g_strdup_printf (_("%.1f PB"), displayed_size);
2356         }
2357       else
2358         {
2359           displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2360           return g_strdup_printf (_("%.1f EB"), displayed_size);
2361         }
2362     }
2363 }
2364
2365 #if defined (G_OS_WIN32) && !defined (_WIN64)
2366
2367 /* Binary compatibility versions. Not for newly compiled code. */
2368
2369 #undef g_find_program_in_path
2370
2371 gchar*
2372 g_find_program_in_path (const gchar *program)
2373 {
2374   gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
2375   gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
2376   gchar *retval;
2377
2378   g_free (utf8_program);
2379   if (utf8_retval == NULL)
2380     return NULL;
2381   retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
2382   g_free (utf8_retval);
2383
2384   return retval;
2385 }
2386
2387 #undef g_get_user_name
2388
2389 const gchar *
2390 g_get_user_name (void)
2391 {
2392   g_get_any_init_locked ();
2393   return g_user_name_cp;
2394 }
2395
2396 #undef g_get_real_name
2397
2398 const gchar *
2399 g_get_real_name (void)
2400 {
2401   g_get_any_init_locked ();
2402   return g_real_name_cp;
2403 }
2404
2405 #undef g_get_home_dir
2406
2407 const gchar *
2408 g_get_home_dir (void)
2409 {
2410   g_get_any_init_locked ();
2411   return g_home_dir_cp;
2412 }
2413
2414 #undef g_get_tmp_dir
2415
2416 const gchar *
2417 g_get_tmp_dir (void)
2418 {
2419   g_get_any_init_locked ();
2420   return g_tmp_dir_cp;
2421 }
2422
2423 #endif
2424
2425 /* Private API:
2426  *
2427  * Returns %TRUE if the current process was executed as setuid (or an
2428  * equivalent __libc_enable_secure is available).  See:
2429  * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
2430  */ 
2431 G_GNUC_INTERNAL gboolean
2432 g_check_setuid (void)
2433 {
2434   /* TODO: get __libc_enable_secure exported from glibc.
2435    * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
2436    */
2437 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
2438   {
2439     /* See glibc/include/unistd.h */
2440     extern int __libc_enable_secure;
2441     return __libc_enable_secure;
2442   }
2443 #elif defined(HAVE_ISSETUGID)
2444   /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2445   return issetugid ();
2446 #elif defined(G_OS_UNIX)
2447   uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2448   gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2449
2450   static gsize check_setuid_initialised;
2451   static gboolean is_setuid;
2452
2453   if (g_once_init_enter (&check_setuid_initialised))
2454     {
2455 #ifdef HAVE_GETRESUID
2456       /* These aren't in the header files, so we prototype them here.
2457        */
2458       int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2459       int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2460       
2461       if (getresuid (&ruid, &euid, &suid) != 0 ||
2462           getresgid (&rgid, &egid, &sgid) != 0)
2463 #endif /* HAVE_GETRESUID */
2464         {
2465           suid = ruid = getuid ();
2466           sgid = rgid = getgid ();
2467           euid = geteuid ();
2468           egid = getegid ();
2469         }
2470
2471       is_setuid = (ruid != euid || ruid != suid ||
2472                    rgid != egid || rgid != sgid);
2473
2474       g_once_init_leave (&check_setuid_initialised, 1);
2475     }
2476   return is_setuid;
2477 #else
2478   return FALSE;
2479 #endif
2480 }