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