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