More header inclusion cleanup
[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 "gfileutils.h"
63 #include "ghash.h"
64 #include "gslist.h"
65 #include "gprintfint.h"
66 #include "gthread.h"
67 #include "gthreadprivate.h"
68 #include "gtestutils.h"
69 #include "gunicode.h"
70 #include "gstrfuncs.h"
71 #include "glibintl.h"
72
73 #ifdef  MAXPATHLEN
74 #define G_PATH_LENGTH   MAXPATHLEN
75 #elif   defined (PATH_MAX)
76 #define G_PATH_LENGTH   PATH_MAX
77 #elif   defined (_PC_PATH_MAX)
78 #define G_PATH_LENGTH   sysconf(_PC_PATH_MAX)
79 #else   
80 #define G_PATH_LENGTH   2048
81 #endif
82
83 #ifdef G_PLATFORM_WIN32
84 #  define STRICT                /* Strict typing, please */
85 #  include <windows.h>
86 #  undef STRICT
87 #  ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
88 #    define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
89 #    define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
90 #  endif
91 #  include <lmcons.h>           /* For UNLEN */
92 #endif /* G_PLATFORM_WIN32 */
93
94 #ifdef G_OS_WIN32
95 #  include <direct.h>
96 #  include <shlobj.h>
97    /* older SDK (e.g. msvc 5.0) does not have these*/
98 #  ifndef CSIDL_MYMUSIC
99 #    define CSIDL_MYMUSIC 13
100 #  endif
101 #  ifndef CSIDL_MYVIDEO
102 #    define CSIDL_MYVIDEO 14
103 #  endif
104 #  ifndef CSIDL_INTERNET_CACHE
105 #    define CSIDL_INTERNET_CACHE 32
106 #  endif
107 #  ifndef CSIDL_COMMON_APPDATA
108 #    define CSIDL_COMMON_APPDATA 35
109 #  endif
110 #  ifndef CSIDL_MYPICTURES
111 #    define CSIDL_MYPICTURES 0x27
112 #  endif
113 #  ifndef CSIDL_COMMON_DOCUMENTS
114 #    define CSIDL_COMMON_DOCUMENTS 46
115 #  endif
116 #  ifndef CSIDL_PROFILE
117 #    define CSIDL_PROFILE 40
118 #  endif
119 #  include <process.h>
120 #endif
121
122 #ifdef HAVE_CARBON
123 #include <CoreServices/CoreServices.h>
124 #endif
125
126 #ifdef HAVE_CODESET
127 #include <langinfo.h>
128 #endif
129
130 const guint glib_major_version = GLIB_MAJOR_VERSION;
131 const guint glib_minor_version = GLIB_MINOR_VERSION;
132 const guint glib_micro_version = GLIB_MICRO_VERSION;
133 const guint glib_interface_age = GLIB_INTERFACE_AGE;
134 const guint glib_binary_age = GLIB_BINARY_AGE;
135
136 #ifdef G_PLATFORM_WIN32
137
138 static HMODULE glib_dll = NULL;
139
140 #ifdef DLL_EXPORT
141
142 BOOL WINAPI
143 DllMain (HINSTANCE hinstDLL,
144          DWORD     fdwReason,
145          LPVOID    lpvReserved)
146 {
147   if (fdwReason == DLL_PROCESS_ATTACH)
148       glib_dll = hinstDLL;
149
150   return TRUE;
151 }
152
153 #endif
154
155 gchar *
156 _glib_get_dll_directory (void)
157 {
158   gchar *retval;
159   gchar *p;
160   wchar_t wc_fn[MAX_PATH];
161
162 #ifdef DLL_EXPORT
163   if (glib_dll == NULL)
164     return NULL;
165 #endif
166
167   /* This code is different from that in
168    * g_win32_get_package_installation_directory_of_module() in that
169    * here we return the actual folder where the GLib DLL is. We don't
170    * do the check for it being in a "bin" or "lib" subfolder and then
171    * returning the parent of that.
172    *
173    * In a statically built GLib, glib_dll will be NULL and we will
174    * thus look up the application's .exe file's location.
175    */
176   if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
177     return NULL;
178
179   retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
180
181   p = strrchr (retval, G_DIR_SEPARATOR);
182   if (p == NULL)
183     {
184       /* Wtf? */
185       return NULL;
186     }
187   *p = '\0';
188
189   return retval;
190 }
191
192 #endif
193
194 /**
195  * glib_check_version:
196  * @required_major: the required major version.
197  * @required_minor: the required minor version.
198  * @required_micro: the required micro version.
199  *
200  * Checks that the GLib library in use is compatible with the
201  * given version. Generally you would pass in the constants
202  * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
203  * as the three arguments to this function; that produces
204  * a check that the library in use is compatible with
205  * the version of GLib the application or module was compiled
206  * against.
207  *
208  * Compatibility is defined by two things: first the version
209  * of the running library is newer than the version
210  * @required_major.required_minor.@required_micro. Second
211  * the running library must be binary compatible with the
212  * version @required_major.required_minor.@required_micro
213  * (same major version.)
214  *
215  * Return value: %NULL if the GLib library is compatible with the
216  *   given version, or a string describing the version mismatch.
217  *   The returned string is owned by GLib and must not be modified
218  *   or freed.
219  *
220  * Since: 2.6
221  **/
222 const gchar *
223 glib_check_version (guint required_major,
224                     guint required_minor,
225                     guint required_micro)
226 {
227   gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
228   gint required_effective_micro = 100 * required_minor + required_micro;
229
230   if (required_major > GLIB_MAJOR_VERSION)
231     return "GLib version too old (major mismatch)";
232   if (required_major < GLIB_MAJOR_VERSION)
233     return "GLib version too new (major mismatch)";
234   if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
235     return "GLib version too new (micro mismatch)";
236   if (required_effective_micro > glib_effective_micro)
237     return "GLib version too old (micro mismatch)";
238   return NULL;
239 }
240
241 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
242 /**
243  * g_memmove: 
244  * @dest: the destination address to copy the bytes to.
245  * @src: the source address to copy the bytes from.
246  * @len: the number of bytes to copy.
247  *
248  * Copies a block of memory @len bytes long, from @src to @dest.
249  * The source and destination areas may overlap.
250  *
251  * In order to use this function, you must include 
252  * <filename>string.h</filename> yourself, because this macro will 
253  * typically simply resolve to memmove() and GLib does not include 
254  * <filename>string.h</filename> for you.
255  */
256 void 
257 g_memmove (gpointer      dest, 
258            gconstpointer src, 
259            gulong        len)
260 {
261   gchar* destptr = dest;
262   const gchar* srcptr = src;
263   if (src + len < dest || dest + len < src)
264     {
265       bcopy (src, dest, len);
266       return;
267     }
268   else if (dest <= src)
269     {
270       while (len--)
271         *(destptr++) = *(srcptr++);
272     }
273   else
274     {
275       destptr += len;
276       srcptr += len;
277       while (len--)
278         *(--destptr) = *(--srcptr);
279     }
280 }
281 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
282
283 #ifdef G_OS_WIN32
284 #undef g_atexit
285 #endif
286
287 /**
288  * g_atexit:
289  * @func: the function to call on normal program termination.
290  * 
291  * Specifies a function to be called at normal program termination.
292  *
293  * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
294  * macro that maps to a call to the atexit() function in the C
295  * library. This means that in case the code that calls g_atexit(),
296  * i.e. atexit(), is in a DLL, the function will be called when the
297  * DLL is detached from the program. This typically makes more sense
298  * than that the function is called when the GLib DLL is detached,
299  * which happened earlier when g_atexit() was a function in the GLib
300  * DLL.
301  *
302  * The behaviour of atexit() in the context of dynamically loaded
303  * modules is not formally specified and varies wildly.
304  *
305  * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
306  * loaded module which is unloaded before the program terminates might
307  * well cause a crash at program exit.
308  *
309  * Some POSIX systems implement atexit() like Windows, and have each
310  * dynamically loaded module maintain an own atexit chain that is
311  * called when the module is unloaded.
312  *
313  * On other POSIX systems, before a dynamically loaded module is
314  * unloaded, the registered atexit functions (if any) residing in that
315  * module are called, regardless where the code that registered them
316  * resided. This is presumably the most robust approach.
317  *
318  * As can be seen from the above, for portability it's best to avoid
319  * calling g_atexit() (or atexit()) except in the main executable of a
320  * program.
321  */
322 void
323 g_atexit (GVoidFunc func)
324 {
325   gint result;
326   const gchar *error = NULL;
327
328   /* keep this in sync with glib.h */
329
330 #ifdef  G_NATIVE_ATEXIT
331   result = ATEXIT (func);
332   if (result)
333     error = g_strerror (errno);
334 #elif defined (HAVE_ATEXIT)
335 #  ifdef NeXT /* @#%@! NeXTStep */
336   result = !atexit ((void (*)(void)) func);
337   if (result)
338     error = g_strerror (errno);
339 #  else
340   result = atexit ((void (*)(void)) func);
341   if (result)
342     error = g_strerror (errno);
343 #  endif /* NeXT */
344 #elif defined (HAVE_ON_EXIT)
345   result = on_exit ((void (*)(int, void *)) func, NULL);
346   if (result)
347     error = g_strerror (errno);
348 #else
349   result = 0;
350   error = "no implementation";
351 #endif /* G_NATIVE_ATEXIT */
352
353   if (error)
354     g_error ("Could not register atexit() function: %s", error);
355 }
356
357 /* Based on execvp() from GNU Libc.
358  * Some of this code is cut-and-pasted into gspawn.c
359  */
360
361 static gchar*
362 my_strchrnul (const gchar *str, 
363               gchar        c)
364 {
365   gchar *p = (gchar*)str;
366   while (*p && (*p != c))
367     ++p;
368
369   return p;
370 }
371
372 #ifdef G_OS_WIN32
373
374 static gchar *inner_find_program_in_path (const gchar *program);
375
376 gchar*
377 g_find_program_in_path (const gchar *program)
378 {
379   const gchar *last_dot = strrchr (program, '.');
380
381   if (last_dot == NULL ||
382       strchr (last_dot, '\\') != NULL ||
383       strchr (last_dot, '/') != NULL)
384     {
385       const gint program_length = strlen (program);
386       gchar *pathext = g_build_path (";",
387                                      ".exe;.cmd;.bat;.com",
388                                      g_getenv ("PATHEXT"),
389                                      NULL);
390       gchar *p;
391       gchar *decorated_program;
392       gchar *retval;
393
394       p = pathext;
395       do
396         {
397           gchar *q = my_strchrnul (p, ';');
398
399           decorated_program = g_malloc (program_length + (q-p) + 1);
400           memcpy (decorated_program, program, program_length);
401           memcpy (decorated_program+program_length, p, q-p);
402           decorated_program [program_length + (q-p)] = '\0';
403           
404           retval = inner_find_program_in_path (decorated_program);
405           g_free (decorated_program);
406
407           if (retval != NULL)
408             {
409               g_free (pathext);
410               return retval;
411             }
412           p = q;
413         } while (*p++ != '\0');
414       g_free (pathext);
415       return NULL;
416     }
417   else
418     return inner_find_program_in_path (program);
419 }
420
421 #endif
422
423 /**
424  * g_find_program_in_path:
425  * @program: a program name in the GLib file name encoding
426  * 
427  * Locates the first executable named @program in the user's path, in the
428  * same way that execvp() would locate it. Returns an allocated string
429  * with the absolute path name, or %NULL if the program is not found in
430  * the path. If @program is already an absolute path, returns a copy of
431  * @program if @program exists and is executable, and %NULL otherwise.
432  *  
433  * On Windows, if @program does not have a file type suffix, tries
434  * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
435  * the <envar>PATHEXT</envar> environment variable. 
436  * 
437  * On Windows, it looks for the file in the same way as CreateProcess() 
438  * would. This means first in the directory where the executing
439  * program was loaded from, then in the current directory, then in the
440  * Windows 32-bit system directory, then in the Windows directory, and
441  * finally in the directories in the <envar>PATH</envar> environment 
442  * variable. If the program is found, the return value contains the 
443  * full name including the type suffix.
444  *
445  * Return value: absolute path, or %NULL
446  **/
447 #ifdef G_OS_WIN32
448 static gchar *
449 inner_find_program_in_path (const gchar *program)
450 #else
451 gchar*
452 g_find_program_in_path (const gchar *program)
453 #endif
454 {
455   const gchar *path, *p;
456   gchar *name, *freeme;
457 #ifdef G_OS_WIN32
458   const gchar *path_copy;
459   gchar *filename = NULL, *appdir = NULL;
460   gchar *sysdir = NULL, *windir = NULL;
461   int n;
462   wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
463     wwindir[MAXPATHLEN];
464 #endif
465   gsize len;
466   gsize pathlen;
467
468   g_return_val_if_fail (program != NULL, NULL);
469
470   /* If it is an absolute path, or a relative path including subdirectories,
471    * don't look in PATH.
472    */
473   if (g_path_is_absolute (program)
474       || strchr (program, G_DIR_SEPARATOR) != NULL
475 #ifdef G_OS_WIN32
476       || strchr (program, '/') != NULL
477 #endif
478       )
479     {
480       if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
481           !g_file_test (program, G_FILE_TEST_IS_DIR))
482         return g_strdup (program);
483       else
484         return NULL;
485     }
486   
487   path = g_getenv ("PATH");
488 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
489   if (path == NULL)
490     {
491       /* There is no `PATH' in the environment.  The default
492        * search path in GNU libc is the current directory followed by
493        * the path `confstr' returns for `_CS_PATH'.
494        */
495       
496       /* In GLib we put . last, for security, and don't use the
497        * unportable confstr(); UNIX98 does not actually specify
498        * what to search if PATH is unset. POSIX may, dunno.
499        */
500       
501       path = "/bin:/usr/bin:.";
502     }
503 #else
504   n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
505   if (n > 0 && n < MAXPATHLEN)
506     filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
507   
508   n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
509   if (n > 0 && n < MAXPATHLEN)
510     sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
511   
512   n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
513   if (n > 0 && n < MAXPATHLEN)
514     windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
515   
516   if (filename)
517     {
518       appdir = g_path_get_dirname (filename);
519       g_free (filename);
520     }
521   
522   path = g_strdup (path);
523
524   if (windir)
525     {
526       const gchar *tem = path;
527       path = g_strconcat (windir, ";", path, NULL);
528       g_free ((gchar *) tem);
529       g_free (windir);
530     }
531   
532   if (sysdir)
533     {
534       const gchar *tem = path;
535       path = g_strconcat (sysdir, ";", path, NULL);
536       g_free ((gchar *) tem);
537       g_free (sysdir);
538     }
539   
540   {
541     const gchar *tem = path;
542     path = g_strconcat (".;", path, NULL);
543     g_free ((gchar *) tem);
544   }
545   
546   if (appdir)
547     {
548       const gchar *tem = path;
549       path = g_strconcat (appdir, ";", path, NULL);
550       g_free ((gchar *) tem);
551       g_free (appdir);
552     }
553
554   path_copy = path;
555 #endif
556   
557   len = strlen (program) + 1;
558   pathlen = strlen (path);
559   freeme = name = g_malloc (pathlen + len + 1);
560   
561   /* Copy the file name at the top, including '\0'  */
562   memcpy (name + pathlen + 1, program, len);
563   name = name + pathlen;
564   /* And add the slash before the filename  */
565   *name = G_DIR_SEPARATOR;
566   
567   p = path;
568   do
569     {
570       char *startp;
571
572       path = p;
573       p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
574
575       if (p == path)
576         /* Two adjacent colons, or a colon at the beginning or the end
577          * of `PATH' means to search the current directory.
578          */
579         startp = name + 1;
580       else
581         startp = memcpy (name - (p - path), path, p - path);
582
583       if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
584           !g_file_test (startp, G_FILE_TEST_IS_DIR))
585         {
586           gchar *ret;
587           ret = g_strdup (startp);
588           g_free (freeme);
589 #ifdef G_OS_WIN32
590           g_free ((gchar *) path_copy);
591 #endif
592           return ret;
593         }
594     }
595   while (*p++ != '\0');
596   
597   g_free (freeme);
598 #ifdef G_OS_WIN32
599   g_free ((gchar *) path_copy);
600 #endif
601
602   return NULL;
603 }
604
605 static gboolean
606 debug_key_matches (const gchar *key,
607                    const gchar *token,
608                    guint        length)
609 {
610   for (; length; length--, key++, token++)
611     {
612       char k = (*key   == '_') ? '-' : tolower (*key  );
613       char t = (*token == '_') ? '-' : tolower (*token);
614
615       if (k != t)
616         return FALSE;
617     }
618
619   return *key == '\0';
620 }
621
622 /**
623  * g_parse_debug_string:
624  * @string: a list of debug options separated by colons, spaces, or
625  * commas, or %NULL.
626  * @keys: pointer to an array of #GDebugKey which associate 
627  *     strings with bit flags.
628  * @nkeys: the number of #GDebugKey<!-- -->s in the array.
629  *
630  * Parses a string containing debugging options
631  * into a %guint containing bit flags. This is used 
632  * within GDK and GTK+ to parse the debug options passed on the
633  * command line or through environment variables.
634  *
635  * If @string is equal to "all", all flags are set.  If @string
636  * is equal to "help", all the available keys in @keys are printed
637  * out to standard error.
638  *
639  * Returns: the combined set of bit flags.
640  */
641 guint        
642 g_parse_debug_string  (const gchar     *string, 
643                        const GDebugKey *keys, 
644                        guint            nkeys)
645 {
646   guint i;
647   guint result = 0;
648   
649   if (string == NULL)
650     return 0;
651
652   /* this function is used by gmem.c/gslice.c initialization code,
653    * so introducing malloc dependencies here would require adaptions
654    * of those code portions.
655    */
656   
657   if (!g_ascii_strcasecmp (string, "all"))
658     {
659       for (i=0; i<nkeys; i++)
660         result |= keys[i].value;
661     }
662   else if (!g_ascii_strcasecmp (string, "help"))
663     {
664       /* using stdio directly for the reason stated above */
665       fprintf (stderr, "Supported debug values: ");
666       for (i=0; i<nkeys; i++)
667         fprintf (stderr, " %s", keys[i].key);
668       fprintf (stderr, "\n");
669     }
670   else
671     {
672       const gchar *p = string;
673       const gchar *q;
674       
675       while (*p)
676         {
677           q = strpbrk (p, ":;, \t");
678           if (!q)
679             q = p + strlen(p);
680           
681           for (i = 0; i < nkeys; i++)
682             if (debug_key_matches (keys[i].key, p, q - p))
683               result |= keys[i].value;
684           
685           p = q;
686           if (*p)
687             p++;
688         }
689     }
690   
691   return result;
692 }
693
694 /**
695  * g_basename:
696  * @file_name: the name of the file.
697  * 
698  * Gets the name of the file without any leading directory components.  
699  * It returns a pointer into the given file name string.
700  * 
701  * Return value: the name of the file without any leading directory components.
702  *
703  * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
704  * g_path_get_basename() allocates new memory for the returned string, unlike
705  * this function which returns a pointer into the argument.
706  **/
707 G_CONST_RETURN gchar*
708 g_basename (const gchar    *file_name)
709 {
710   register gchar *base;
711   
712   g_return_val_if_fail (file_name != NULL, NULL);
713   
714   base = strrchr (file_name, G_DIR_SEPARATOR);
715
716 #ifdef G_OS_WIN32
717   {
718     gchar *q = strrchr (file_name, '/');
719     if (base == NULL || (q != NULL && q > base))
720         base = q;
721   }
722 #endif
723
724   if (base)
725     return base + 1;
726
727 #ifdef G_OS_WIN32
728   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
729     return (gchar*) file_name + 2;
730 #endif /* G_OS_WIN32 */
731   
732   return (gchar*) file_name;
733 }
734
735 /**
736  * g_path_get_basename:
737  * @file_name: the name of the file.
738  *
739  * Gets the last component of the filename. If @file_name ends with a 
740  * directory separator it gets the component before the last slash. If 
741  * @file_name consists only of directory separators (and on Windows, 
742  * possibly a drive letter), a single separator is returned. If
743  * @file_name is empty, it gets ".".
744  *
745  * Return value: a newly allocated string containing the last component of 
746  *   the filename.
747  */
748 gchar*
749 g_path_get_basename (const gchar   *file_name)
750 {
751   register gssize base;             
752   register gssize last_nonslash;    
753   gsize len;    
754   gchar *retval;
755  
756   g_return_val_if_fail (file_name != NULL, NULL);
757
758   if (file_name[0] == '\0')
759     /* empty string */
760     return g_strdup (".");
761   
762   last_nonslash = strlen (file_name) - 1;
763
764   while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
765     last_nonslash--;
766
767   if (last_nonslash == -1)
768     /* string only containing slashes */
769     return g_strdup (G_DIR_SEPARATOR_S);
770
771 #ifdef G_OS_WIN32
772   if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
773     /* string only containing slashes and a drive */
774     return g_strdup (G_DIR_SEPARATOR_S);
775 #endif /* G_OS_WIN32 */
776
777   base = last_nonslash;
778
779   while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
780     base--;
781
782 #ifdef G_OS_WIN32
783   if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
784     base = 1;
785 #endif /* G_OS_WIN32 */
786
787   len = last_nonslash - base;
788   retval = g_malloc (len + 1);
789   memcpy (retval, file_name + base + 1, len);
790   retval [len] = '\0';
791   return retval;
792 }
793
794 /**
795  * g_path_is_absolute:
796  * @file_name: a file name.
797  *
798  * Returns %TRUE if the given @file_name is an absolute file name,
799  * i.e. it contains a full path from the root directory such as "/usr/local"
800  * on UNIX or "C:\windows" on Windows systems.
801  *
802  * Returns: %TRUE if @file_name is an absolute path. 
803  */
804 gboolean
805 g_path_is_absolute (const gchar *file_name)
806 {
807   g_return_val_if_fail (file_name != NULL, FALSE);
808   
809   if (G_IS_DIR_SEPARATOR (file_name[0]))
810     return TRUE;
811
812 #ifdef G_OS_WIN32
813   /* Recognize drive letter on native Windows */
814   if (g_ascii_isalpha (file_name[0]) && 
815       file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
816     return TRUE;
817 #endif /* G_OS_WIN32 */
818
819   return FALSE;
820 }
821
822 /**
823  * g_path_skip_root:
824  * @file_name: a file name.
825  *
826  * Returns a pointer into @file_name after the root component, i.e. after
827  * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
828  * path it returns %NULL.
829  *
830  * Returns: a pointer into @file_name after the root component.
831  */
832 G_CONST_RETURN gchar*
833 g_path_skip_root (const gchar *file_name)
834 {
835   g_return_val_if_fail (file_name != NULL, NULL);
836   
837 #ifdef G_PLATFORM_WIN32
838   /* Skip \\server\share or //server/share */
839   if (G_IS_DIR_SEPARATOR (file_name[0]) &&
840       G_IS_DIR_SEPARATOR (file_name[1]) &&
841       file_name[2] &&
842       !G_IS_DIR_SEPARATOR (file_name[2]))
843     {
844       gchar *p;
845
846       p = strchr (file_name + 2, G_DIR_SEPARATOR);
847 #ifdef G_OS_WIN32
848       {
849         gchar *q = strchr (file_name + 2, '/');
850         if (p == NULL || (q != NULL && q < p))
851           p = q;
852       }
853 #endif
854       if (p &&
855           p > file_name + 2 &&
856           p[1])
857         {
858           file_name = p + 1;
859
860           while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
861             file_name++;
862
863           /* Possibly skip a backslash after the share name */
864           if (G_IS_DIR_SEPARATOR (file_name[0]))
865             file_name++;
866
867           return (gchar *)file_name;
868         }
869     }
870 #endif
871   
872   /* Skip initial slashes */
873   if (G_IS_DIR_SEPARATOR (file_name[0]))
874     {
875       while (G_IS_DIR_SEPARATOR (file_name[0]))
876         file_name++;
877       return (gchar *)file_name;
878     }
879
880 #ifdef G_OS_WIN32
881   /* Skip X:\ */
882   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
883     return (gchar *)file_name + 3;
884 #endif
885
886   return NULL;
887 }
888
889 /**
890  * g_path_get_dirname:
891  * @file_name: the name of the file.
892  *
893  * Gets the directory components of a file name.  If the file name has no
894  * directory components "." is returned.  The returned string should be
895  * freed when no longer needed.
896  * 
897  * Returns: the directory components of the file.
898  */
899 gchar*
900 g_path_get_dirname (const gchar    *file_name)
901 {
902   register gchar *base;
903   register gsize len;    
904   
905   g_return_val_if_fail (file_name != NULL, NULL);
906   
907   base = strrchr (file_name, G_DIR_SEPARATOR);
908 #ifdef G_OS_WIN32
909   {
910     gchar *q = strrchr (file_name, '/');
911     if (base == NULL || (q != NULL && q > base))
912         base = q;
913   }
914 #endif
915   if (!base)
916     {
917 #ifdef G_OS_WIN32
918       if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
919         {
920           gchar drive_colon_dot[4];
921
922           drive_colon_dot[0] = file_name[0];
923           drive_colon_dot[1] = ':';
924           drive_colon_dot[2] = '.';
925           drive_colon_dot[3] = '\0';
926
927           return g_strdup (drive_colon_dot);
928         }
929 #endif
930     return g_strdup (".");
931     }
932
933   while (base > file_name && G_IS_DIR_SEPARATOR (*base))
934     base--;
935
936 #ifdef G_OS_WIN32
937   /* base points to the char before the last slash.
938    *
939    * In case file_name is the root of a drive (X:\) or a child of the
940    * root of a drive (X:\foo), include the slash.
941    *
942    * In case file_name is the root share of an UNC path
943    * (\\server\share), add a slash, returning \\server\share\ .
944    *
945    * In case file_name is a direct child of a share in an UNC path
946    * (\\server\share\foo), include the slash after the share name,
947    * returning \\server\share\ .
948    */
949   if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
950     base++;
951   else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
952            G_IS_DIR_SEPARATOR (file_name[1]) &&
953            file_name[2] &&
954            !G_IS_DIR_SEPARATOR (file_name[2]) &&
955            base >= file_name + 2)
956     {
957       const gchar *p = file_name + 2;
958       while (*p && !G_IS_DIR_SEPARATOR (*p))
959         p++;
960       if (p == base + 1)
961         {
962           len = (guint) strlen (file_name) + 1;
963           base = g_new (gchar, len + 1);
964           strcpy (base, file_name);
965           base[len-1] = G_DIR_SEPARATOR;
966           base[len] = 0;
967           return base;
968         }
969       if (G_IS_DIR_SEPARATOR (*p))
970         {
971           p++;
972           while (*p && !G_IS_DIR_SEPARATOR (*p))
973             p++;
974           if (p == base + 1)
975             base++;
976         }
977     }
978 #endif
979
980   len = (guint) 1 + base - file_name;
981   
982   base = g_new (gchar, len + 1);
983   g_memmove (base, file_name, len);
984   base[len] = 0;
985   
986   return base;
987 }
988
989 /**
990  * g_get_current_dir:
991  *
992  * Gets the current directory.
993  * The returned string should be freed when no longer needed. The encoding 
994  * of the returned string is system defined. On Windows, it is always UTF-8.
995  * 
996  * Returns: the current directory.
997  */
998 gchar*
999 g_get_current_dir (void)
1000 {
1001 #ifdef G_OS_WIN32
1002
1003   gchar *dir = NULL;
1004   wchar_t dummy[2], *wdir;
1005   int len;
1006
1007   len = GetCurrentDirectoryW (2, dummy);
1008   wdir = g_new (wchar_t, len);
1009
1010   if (GetCurrentDirectoryW (len, wdir) == len - 1)
1011     dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
1012   
1013   g_free (wdir);
1014
1015   if (dir == NULL)
1016     dir = g_strdup ("\\");
1017
1018   return dir;
1019
1020 #else
1021
1022   gchar *buffer = NULL;
1023   gchar *dir = NULL;
1024   static gulong max_len = 0;
1025
1026   if (max_len == 0) 
1027     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
1028   
1029   /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
1030    * and, if that wasn't bad enough, hangs in doing so.
1031    */
1032 #if     (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1033   buffer = g_new (gchar, max_len + 1);
1034   *buffer = 0;
1035   dir = getwd (buffer);
1036 #else   /* !sun || !HAVE_GETCWD */
1037   while (max_len < G_MAXULONG / 2)
1038     {
1039       g_free (buffer);
1040       buffer = g_new (gchar, max_len + 1);
1041       *buffer = 0;
1042       dir = getcwd (buffer, max_len);
1043
1044       if (dir || errno != ERANGE)
1045         break;
1046
1047       max_len *= 2;
1048     }
1049 #endif  /* !sun || !HAVE_GETCWD */
1050   
1051   if (!dir || !*buffer)
1052     {
1053       /* hm, should we g_error() out here?
1054        * this can happen if e.g. "./" has mode \0000
1055        */
1056       buffer[0] = G_DIR_SEPARATOR;
1057       buffer[1] = 0;
1058     }
1059
1060   dir = g_strdup (buffer);
1061   g_free (buffer);
1062   
1063   return dir;
1064 #endif /* !Win32 */
1065 }
1066
1067 /**
1068  * g_getenv:
1069  * @variable: the environment variable to get, in the GLib file name encoding.
1070  * 
1071  * Returns the value of an environment variable. The name and value
1072  * are in the GLib file name encoding. On UNIX, this means the actual
1073  * bytes which might or might not be in some consistent character set
1074  * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1075  * environment variable's value contains references to other
1076  * environment variables, they are expanded.
1077  * 
1078  * Return value: the value of the environment variable, or %NULL if
1079  * the environment variable is not found. The returned string may be
1080  * overwritten by the next call to g_getenv(), g_setenv() or
1081  * g_unsetenv().
1082  **/
1083 G_CONST_RETURN gchar*
1084 g_getenv (const gchar *variable)
1085 {
1086 #ifndef G_OS_WIN32
1087
1088   g_return_val_if_fail (variable != NULL, NULL);
1089
1090   return getenv (variable);
1091
1092 #else /* G_OS_WIN32 */
1093
1094   GQuark quark;
1095   gchar *value;
1096   wchar_t dummy[2], *wname, *wvalue;
1097   int len;
1098
1099   g_return_val_if_fail (variable != NULL, NULL);
1100   g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1101
1102   /* On Windows NT, it is relatively typical that environment
1103    * variables contain references to other environment variables. If
1104    * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1105    * environment variables would be stored in the Registry as
1106    * REG_EXPAND_SZ type values, and would then get automatically
1107    * expanded before a program sees them. But there is broken software
1108    * that stores environment variables as REG_SZ values even if they
1109    * contain references to other environment variables.)
1110    */
1111
1112   wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1113
1114   len = GetEnvironmentVariableW (wname, dummy, 2);
1115
1116   if (len == 0)
1117     {
1118       g_free (wname);
1119       return NULL;
1120     }
1121   else if (len == 1)
1122     len = 2;
1123
1124   wvalue = g_new (wchar_t, len);
1125
1126   if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1127     {
1128       g_free (wname);
1129       g_free (wvalue);
1130       return NULL;
1131     }
1132
1133   if (wcschr (wvalue, L'%') != NULL)
1134     {
1135       wchar_t *tem = wvalue;
1136
1137       len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1138
1139       if (len > 0)
1140         {
1141           wvalue = g_new (wchar_t, len);
1142
1143           if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1144             {
1145               g_free (wvalue);
1146               wvalue = tem;
1147             }
1148           else
1149             g_free (tem);
1150         }
1151     }
1152
1153   value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1154
1155   g_free (wname);
1156   g_free (wvalue);
1157
1158   quark = g_quark_from_string (value);
1159   g_free (value);
1160   
1161   return g_quark_to_string (quark);
1162
1163 #endif /* G_OS_WIN32 */
1164 }
1165
1166 /* _g_getenv_nomalloc
1167  * this function does a getenv() without doing any kind of allocation
1168  * through glib. it's suitable for chars <= 127 only (both, for the
1169  * variable name and the contents) and for contents < 1024 chars in
1170  * length. also, it aliases "" to a NULL return value.
1171  **/
1172 const gchar*
1173 _g_getenv_nomalloc (const gchar *variable,
1174                     gchar        buffer[1024])
1175 {
1176   const gchar *retval = getenv (variable);
1177   if (retval && retval[0])
1178     {
1179       gint l = strlen (retval);
1180       if (l < 1024)
1181         {
1182           strncpy (buffer, retval, l);
1183           buffer[l] = 0;
1184           return buffer;
1185         }
1186     }
1187   return NULL;
1188 }
1189
1190 /**
1191  * g_setenv:
1192  * @variable: the environment variable to set, must not contain '='.
1193  * @value: the value for to set the variable to.
1194  * @overwrite: whether to change the variable if it already exists.
1195  *
1196  * Sets an environment variable. Both the variable's name and value
1197  * should be in the GLib file name encoding. On UNIX, this means that
1198  * they can be any sequence of bytes. On Windows, they should be in
1199  * UTF-8.
1200  *
1201  * Note that on some systems, when variables are overwritten, the memory 
1202  * used for the previous variables and its value isn't reclaimed.
1203  *
1204  * Returns: %FALSE if the environment variable couldn't be set.
1205  *
1206  * Since: 2.4
1207  */
1208 gboolean
1209 g_setenv (const gchar *variable, 
1210           const gchar *value, 
1211           gboolean     overwrite)
1212 {
1213 #ifndef G_OS_WIN32
1214
1215   gint result;
1216 #ifndef HAVE_SETENV
1217   gchar *string;
1218 #endif
1219
1220   g_return_val_if_fail (variable != NULL, FALSE);
1221   g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1222
1223 #ifdef HAVE_SETENV
1224   result = setenv (variable, value, overwrite);
1225 #else
1226   if (!overwrite && getenv (variable) != NULL)
1227     return TRUE;
1228   
1229   /* This results in a leak when you overwrite existing
1230    * settings. It would be fairly easy to fix this by keeping
1231    * our own parallel array or hash table.
1232    */
1233   string = g_strconcat (variable, "=", value, NULL);
1234   result = putenv (string);
1235 #endif
1236   return result == 0;
1237
1238 #else /* G_OS_WIN32 */
1239
1240   gboolean retval;
1241   wchar_t *wname, *wvalue, *wassignment;
1242   gchar *tem;
1243
1244   g_return_val_if_fail (variable != NULL, FALSE);
1245   g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1246   g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1247   g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1248
1249   if (!overwrite && g_getenv (variable) != NULL)
1250     return TRUE;
1251
1252   /* We want to (if possible) set both the environment variable copy
1253    * kept by the C runtime and the one kept by the system.
1254    *
1255    * We can't use only the C runtime's putenv or _wputenv() as that
1256    * won't work for arbitrary Unicode strings in a "non-Unicode" app
1257    * (with main() and not wmain()). In a "main()" app the C runtime
1258    * initializes the C runtime's environment table by converting the
1259    * real (wide char) environment variables to system codepage, thus
1260    * breaking those that aren't representable in the system codepage.
1261    *
1262    * As the C runtime's putenv() will also set the system copy, we do
1263    * the putenv() first, then call SetEnvironmentValueW ourselves.
1264    */
1265
1266   wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1267   wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1268   tem = g_strconcat (variable, "=", value, NULL);
1269   wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1270     
1271   g_free (tem);
1272   _wputenv (wassignment);
1273   g_free (wassignment);
1274
1275   retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1276
1277   g_free (wname);
1278   g_free (wvalue);
1279
1280   return retval;
1281
1282 #endif /* G_OS_WIN32 */
1283 }
1284
1285 #ifdef HAVE__NSGETENVIRON
1286 #define environ (*_NSGetEnviron())
1287 #elif !defined(G_OS_WIN32)
1288
1289 /* According to the Single Unix Specification, environ is not in 
1290  * any system header, although unistd.h often declares it.
1291  */
1292 extern char **environ;
1293 #endif
1294
1295 /**
1296  * g_unsetenv:
1297  * @variable: the environment variable to remove, must not contain '='.
1298  * 
1299  * Removes an environment variable from the environment.
1300  *
1301  * Note that on some systems, when variables are overwritten, the memory 
1302  * used for the previous variables and its value isn't reclaimed.
1303  * Furthermore, this function can't be guaranteed to operate in a 
1304  * threadsafe way.
1305  *
1306  * Since: 2.4 
1307  **/
1308 void
1309 g_unsetenv (const gchar *variable)
1310 {
1311 #ifndef G_OS_WIN32
1312
1313 #ifdef HAVE_UNSETENV
1314   g_return_if_fail (variable != NULL);
1315   g_return_if_fail (strchr (variable, '=') == NULL);
1316
1317   unsetenv (variable);
1318 #else /* !HAVE_UNSETENV */
1319   int len;
1320   gchar **e, **f;
1321
1322   g_return_if_fail (variable != NULL);
1323   g_return_if_fail (strchr (variable, '=') == NULL);
1324
1325   len = strlen (variable);
1326   
1327   /* Mess directly with the environ array.
1328    * This seems to be the only portable way to do this.
1329    *
1330    * Note that we remove *all* environment entries for
1331    * the variable name, not just the first.
1332    */
1333   e = f = environ;
1334   while (*e != NULL) 
1335     {
1336       if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=') 
1337         {
1338           *f = *e;
1339           f++;
1340         }
1341       e++;
1342     }
1343   *f = NULL;
1344 #endif /* !HAVE_UNSETENV */
1345
1346 #else  /* G_OS_WIN32 */
1347
1348   wchar_t *wname, *wassignment;
1349   gchar *tem;
1350
1351   g_return_if_fail (variable != NULL);
1352   g_return_if_fail (strchr (variable, '=') == NULL);
1353   g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1354
1355   wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1356   tem = g_strconcat (variable, "=", NULL);
1357   wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1358     
1359   g_free (tem);
1360   _wputenv (wassignment);
1361   g_free (wassignment);
1362
1363   SetEnvironmentVariableW (wname, NULL);
1364
1365   g_free (wname);
1366
1367 #endif /* G_OS_WIN32 */
1368 }
1369
1370 /**
1371  * g_listenv:
1372  *
1373  * Gets the names of all variables set in the environment.
1374  * 
1375  * Returns: a %NULL-terminated list of strings which must be freed
1376  * with g_strfreev().
1377  *
1378  * Programs that want to be portable to Windows should typically use
1379  * this function and g_getenv() instead of using the environ array
1380  * from the C library directly. On Windows, the strings in the environ
1381  * array are in system codepage encoding, while in most of the typical
1382  * use cases for environment variables in GLib-using programs you want
1383  * the UTF-8 encoding that this function and g_getenv() provide.
1384  *
1385  * Since: 2.8
1386  */
1387 gchar **
1388 g_listenv (void)
1389 {
1390 #ifndef G_OS_WIN32
1391   gchar **result, *eq;
1392   gint len, i, j;
1393
1394   len = g_strv_length (environ);
1395   result = g_new0 (gchar *, len + 1);
1396   
1397   j = 0;
1398   for (i = 0; i < len; i++)
1399     {
1400       eq = strchr (environ[i], '=');
1401       if (eq)
1402         result[j++] = g_strndup (environ[i], eq - environ[i]);
1403     }
1404
1405   result[j] = NULL;
1406
1407   return result;
1408 #else
1409   gchar **result, *eq;
1410   gint len = 0, j;
1411   wchar_t *p, *q;
1412
1413   p = (wchar_t *) GetEnvironmentStringsW ();
1414   if (p != NULL)
1415     {
1416       q = p;
1417       while (*q)
1418         {
1419           q += wcslen (q) + 1;
1420           len++;
1421         }
1422     }
1423   result = g_new0 (gchar *, len + 1);
1424
1425   j = 0;
1426   q = p;
1427   while (*q)
1428     {
1429       result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1430       if (result[j] != NULL)
1431         {
1432           eq = strchr (result[j], '=');
1433           if (eq && eq > result[j])
1434             {
1435               *eq = '\0';
1436               j++;
1437             }
1438           else
1439             g_free (result[j]);
1440         }
1441       q += wcslen (q) + 1;
1442     }
1443   result[j] = NULL;
1444   FreeEnvironmentStringsW (p);
1445
1446   return result;
1447 #endif
1448 }
1449
1450 G_LOCK_DEFINE_STATIC (g_utils_global);
1451
1452 static  gchar   *g_tmp_dir = NULL;
1453 static  gchar   *g_user_name = NULL;
1454 static  gchar   *g_real_name = NULL;
1455 static  gchar   *g_home_dir = NULL;
1456 static  gchar   *g_host_name = NULL;
1457
1458 #ifdef G_OS_WIN32
1459 /* System codepage versions of the above, kept at file level so that they,
1460  * too, are produced only once.
1461  */
1462 static  gchar   *g_tmp_dir_cp = NULL;
1463 static  gchar   *g_user_name_cp = NULL;
1464 static  gchar   *g_real_name_cp = NULL;
1465 static  gchar   *g_home_dir_cp = NULL;
1466 #endif
1467
1468 static  gchar   *g_user_data_dir = NULL;
1469 static  gchar  **g_system_data_dirs = NULL;
1470 static  gchar   *g_user_cache_dir = NULL;
1471 static  gchar   *g_user_config_dir = NULL;
1472 static  gchar  **g_system_config_dirs = NULL;
1473
1474 static  gchar  **g_user_special_dirs = NULL;
1475
1476 /* fifteen minutes of fame for everybody */
1477 #define G_USER_DIRS_EXPIRE      15 * 60
1478
1479 #ifdef G_OS_WIN32
1480
1481 static gchar *
1482 get_special_folder (int csidl)
1483 {
1484   wchar_t path[MAX_PATH+1];
1485   HRESULT hr;
1486   LPITEMIDLIST pidl = NULL;
1487   BOOL b;
1488   gchar *retval = NULL;
1489
1490   hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1491   if (hr == S_OK)
1492     {
1493       b = SHGetPathFromIDListW (pidl, path);
1494       if (b)
1495         retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1496       CoTaskMemFree (pidl);
1497     }
1498   return retval;
1499 }
1500
1501 static char *
1502 get_windows_directory_root (void)
1503 {
1504   wchar_t wwindowsdir[MAX_PATH];
1505
1506   if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1507     {
1508       /* Usually X:\Windows, but in terminal server environments
1509        * might be an UNC path, AFAIK.
1510        */
1511       char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1512       char *p;
1513
1514       if (windowsdir == NULL)
1515         return g_strdup ("C:\\");
1516
1517       p = (char *) g_path_skip_root (windowsdir);
1518       if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1519         p--;
1520       *p = '\0';
1521       return windowsdir;
1522     }
1523   else
1524     return g_strdup ("C:\\");
1525 }
1526
1527 #endif
1528
1529 /* HOLDS: g_utils_global_lock */
1530 static void
1531 g_get_any_init_do (void)
1532 {
1533   gchar hostname[100];
1534
1535   g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1536   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1537     g_tmp_dir = g_strdup (g_getenv ("TMP"));
1538   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1539     g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1540
1541 #ifdef G_OS_WIN32
1542   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1543     g_tmp_dir = get_windows_directory_root ();
1544 #else  
1545 #ifdef P_tmpdir
1546   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1547     {
1548       gsize k;    
1549       g_tmp_dir = g_strdup (P_tmpdir);
1550       k = strlen (g_tmp_dir);
1551       if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1552         g_tmp_dir[k - 1] = '\0';
1553     }
1554 #endif
1555   
1556   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1557     {
1558       g_tmp_dir = g_strdup ("/tmp");
1559     }
1560 #endif  /* !G_OS_WIN32 */
1561   
1562 #ifdef G_OS_WIN32
1563   /* We check $HOME first for Win32, though it is a last resort for Unix
1564    * where we prefer the results of getpwuid().
1565    */
1566   g_home_dir = g_strdup (g_getenv ("HOME"));
1567
1568   /* Only believe HOME if it is an absolute path and exists */
1569   if (g_home_dir)
1570     {
1571       if (!(g_path_is_absolute (g_home_dir) &&
1572             g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1573         {
1574           g_free (g_home_dir);
1575           g_home_dir = NULL;
1576         }
1577     }
1578   
1579   /* In case HOME is Unix-style (it happens), convert it to
1580    * Windows style.
1581    */
1582   if (g_home_dir)
1583     {
1584       gchar *p;
1585       while ((p = strchr (g_home_dir, '/')) != NULL)
1586         *p = '\\';
1587     }
1588
1589   if (!g_home_dir)
1590     {
1591       /* USERPROFILE is probably the closest equivalent to $HOME? */
1592       if (g_getenv ("USERPROFILE") != NULL)
1593         g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1594     }
1595
1596   if (!g_home_dir)
1597     g_home_dir = get_special_folder (CSIDL_PROFILE);
1598   
1599   if (!g_home_dir)
1600     g_home_dir = get_windows_directory_root ();
1601 #endif /* G_OS_WIN32 */
1602   
1603 #ifdef HAVE_PWD_H
1604   {
1605     struct passwd *pw = NULL;
1606     gpointer buffer = NULL;
1607     gint error;
1608     gchar *logname;
1609
1610 #  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1611     struct passwd pwd;
1612 #    ifdef _SC_GETPW_R_SIZE_MAX  
1613     /* This reurns the maximum length */
1614     glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1615     
1616     if (bufsize < 0)
1617       bufsize = 64;
1618 #    else /* _SC_GETPW_R_SIZE_MAX */
1619     glong bufsize = 64;
1620 #    endif /* _SC_GETPW_R_SIZE_MAX */
1621
1622     logname = (gchar *) g_getenv ("LOGNAME");
1623         
1624     do
1625       {
1626         g_free (buffer);
1627         /* we allocate 6 extra bytes to work around a bug in 
1628          * Mac OS < 10.3. See #156446
1629          */
1630         buffer = g_malloc (bufsize + 6);
1631         errno = 0;
1632         
1633 #    ifdef HAVE_POSIX_GETPWUID_R
1634         if (logname) {
1635           error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1636           if (!pw || (pw->pw_uid != getuid ())) {
1637             /* LOGNAME is lying, fall back to looking up the uid */
1638             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1639           }
1640         } else {
1641           error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1642         }
1643         error = error < 0 ? errno : error;
1644 #    else /* HAVE_NONPOSIX_GETPWUID_R */
1645    /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1646 #      if defined(_AIX) || defined(__hpux)
1647         error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1648         pw = error == 0 ? &pwd : NULL;
1649 #      else /* !_AIX */
1650         if (logname) {
1651           pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1652           if (!pw || (pw->pw_uid != getuid ())) {
1653             /* LOGNAME is lying, fall back to looking up the uid */
1654             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1655           }
1656         } else {
1657           pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1658         }
1659         error = pw ? 0 : errno;
1660 #      endif /* !_AIX */            
1661 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
1662         
1663         if (!pw)
1664           {
1665             /* we bail out prematurely if the user id can't be found
1666              * (should be pretty rare case actually), or if the buffer
1667              * should be sufficiently big and lookups are still not
1668              * successfull.
1669              */
1670             if (error == 0 || error == ENOENT)
1671               {
1672                 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1673                            (gulong) getuid ());
1674                 break;
1675               }
1676             if (bufsize > 32 * 1024)
1677               {
1678                 g_warning ("getpwuid_r(): failed due to: %s.",
1679                            g_strerror (error));
1680                 break;
1681               }
1682             
1683             bufsize *= 2;
1684           }
1685       }
1686     while (!pw);
1687 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1688     
1689     if (!pw)
1690       {
1691         setpwent ();
1692         pw = getpwuid (getuid ());
1693         endpwent ();
1694       }
1695     if (pw)
1696       {
1697         g_user_name = g_strdup (pw->pw_name);
1698
1699         if (pw->pw_gecos && *pw->pw_gecos != '\0') 
1700           {
1701             gchar **gecos_fields;
1702             gchar **name_parts;
1703
1704             /* split the gecos field and substitute '&' */
1705             gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1706             name_parts = g_strsplit (gecos_fields[0], "&", 0);
1707             pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1708             g_real_name = g_strjoinv (pw->pw_name, name_parts);
1709             g_strfreev (gecos_fields);
1710             g_strfreev (name_parts);
1711           }
1712
1713         if (!g_home_dir)
1714           g_home_dir = g_strdup (pw->pw_dir);
1715       }
1716     g_free (buffer);
1717   }
1718   
1719 #else /* !HAVE_PWD_H */
1720   
1721 #ifdef G_OS_WIN32
1722   {
1723     guint len = UNLEN+1;
1724     wchar_t buffer[UNLEN+1];
1725     
1726     if (GetUserNameW (buffer, (LPDWORD) &len))
1727       {
1728         g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1729         g_real_name = g_strdup (g_user_name);
1730       }
1731   }
1732 #endif /* G_OS_WIN32 */
1733
1734 #endif /* !HAVE_PWD_H */
1735
1736 #ifndef G_OS_WIN32
1737   if (!g_home_dir)
1738     g_home_dir = g_strdup (g_getenv ("HOME"));
1739 #endif
1740
1741 #ifdef __EMX__
1742   /* change '\\' in %HOME% to '/' */
1743   g_strdelimit (g_home_dir, "\\",'/');
1744 #endif
1745   if (!g_user_name)
1746     g_user_name = g_strdup ("somebody");
1747   if (!g_real_name)
1748     g_real_name = g_strdup ("Unknown");
1749
1750   {
1751 #ifndef G_OS_WIN32
1752     gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1753 #else
1754     DWORD size = sizeof (hostname);
1755     gboolean hostname_fail = (!GetComputerName (hostname, &size));
1756 #endif
1757     g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1758   }
1759
1760 #ifdef G_OS_WIN32
1761   g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1762   g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1763   g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1764
1765   if (!g_tmp_dir_cp)
1766     g_tmp_dir_cp = g_strdup ("\\");
1767   if (!g_user_name_cp)
1768     g_user_name_cp = g_strdup ("somebody");
1769   if (!g_real_name_cp)
1770     g_real_name_cp = g_strdup ("Unknown");
1771
1772   /* home_dir might be NULL, unlike tmp_dir, user_name and
1773    * real_name.
1774    */
1775   if (g_home_dir)
1776     g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1777   else
1778     g_home_dir_cp = NULL;
1779 #endif /* G_OS_WIN32 */
1780 }
1781
1782 static inline void
1783 g_get_any_init (void)
1784 {
1785   if (!g_tmp_dir)
1786     g_get_any_init_do ();
1787 }
1788
1789 static inline void
1790 g_get_any_init_locked (void)
1791 {
1792   G_LOCK (g_utils_global);
1793   g_get_any_init ();
1794   G_UNLOCK (g_utils_global);
1795 }
1796
1797
1798 /**
1799  * g_get_user_name:
1800  *
1801  * Gets the user name of the current user. The encoding of the returned
1802  * string is system-defined. On UNIX, it might be the preferred file name
1803  * encoding, or something else, and there is no guarantee that it is even
1804  * consistent on a machine. On Windows, it is always UTF-8.
1805  *
1806  * Returns: the user name of the current user.
1807  */
1808 G_CONST_RETURN gchar*
1809 g_get_user_name (void)
1810 {
1811   g_get_any_init_locked ();
1812   return g_user_name;
1813 }
1814
1815 /**
1816  * g_get_real_name:
1817  *
1818  * Gets the real name of the user. This usually comes from the user's entry 
1819  * in the <filename>passwd</filename> file. The encoding of the returned 
1820  * string is system-defined. (On Windows, it is, however, always UTF-8.) 
1821  * If the real user name cannot be determined, the string "Unknown" is 
1822  * returned.
1823  *
1824  * Returns: the user's real name.
1825  */
1826 G_CONST_RETURN gchar*
1827 g_get_real_name (void)
1828 {
1829   g_get_any_init_locked ();
1830   return g_real_name;
1831 }
1832
1833 /**
1834  * g_get_home_dir:
1835  *
1836  * Gets the current user's home directory as defined in the 
1837  * password database.
1838  *
1839  * Note that in contrast to traditional UNIX tools, this function 
1840  * prefers <filename>passwd</filename> entries over the <envar>HOME</envar> 
1841  * environment variable. 
1842  *
1843  * One of the reasons for this decision is that applications in many 
1844  * cases need special handling to deal with the case where 
1845  * <envar>HOME</envar> is
1846  * <simplelist>
1847  *   <member>Not owned by the user</member>
1848  *   <member>Not writeable</member>
1849  *   <member>Not even readable</member>
1850  * </simplelist>
1851  * Since applications are in general <emphasis>not</emphasis> written 
1852  * to deal with these situations it was considered better to make 
1853  * g_get_home_dir() not pay attention to <envar>HOME</envar> and to 
1854  * return the real home directory for the user. If applications
1855  * want to pay attention to <envar>HOME</envar>, they can do:
1856  * |[
1857  *  const char *homedir = g_getenv ("HOME");
1858  *   if (!homedir)
1859  *      homedir = g_get_home_dir (<!-- -->);
1860  * ]|
1861  *
1862  * Returns: the current user's home directory
1863  */
1864 G_CONST_RETURN gchar*
1865 g_get_home_dir (void)
1866 {
1867   g_get_any_init_locked ();
1868   return g_home_dir;
1869 }
1870
1871 /**
1872  * g_get_tmp_dir:
1873  *
1874  * Gets the directory to use for temporary files. This is found from 
1875  * inspecting the environment variables <envar>TMPDIR</envar>, 
1876  * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none 
1877  * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows. 
1878  * The encoding of the returned string is system-defined. On Windows, 
1879  * it is always UTF-8. The return value is never %NULL or the empty string.
1880  *
1881  * Returns: the directory to use for temporary files.
1882  */
1883 G_CONST_RETURN gchar*
1884 g_get_tmp_dir (void)
1885 {
1886   g_get_any_init_locked ();
1887   return g_tmp_dir;
1888 }
1889
1890 /**
1891  * g_get_host_name:
1892  *
1893  * Return a name for the machine. 
1894  *
1895  * The returned name is not necessarily a fully-qualified domain name,
1896  * or even present in DNS or some other name service at all. It need
1897  * not even be unique on your local network or site, but usually it
1898  * is. Callers should not rely on the return value having any specific
1899  * properties like uniqueness for security purposes. Even if the name
1900  * of the machine is changed while an application is running, the
1901  * return value from this function does not change. The returned
1902  * string is owned by GLib and should not be modified or freed. If no
1903  * name can be determined, a default fixed string "localhost" is
1904  * returned.
1905  *
1906  * Returns: the host name of the machine.
1907  *
1908  * Since: 2.8
1909  */
1910 const gchar *
1911 g_get_host_name (void)
1912 {
1913   g_get_any_init_locked ();
1914   return g_host_name;
1915 }
1916
1917 G_LOCK_DEFINE_STATIC (g_prgname);
1918 static gchar *g_prgname = NULL;
1919
1920 /**
1921  * g_get_prgname:
1922  *
1923  * Gets the name of the program. This name should <emphasis>not</emphasis> 
1924  * be localized, contrast with g_get_application_name().
1925  * (If you are using GDK or GTK+ the program name is set in gdk_init(), 
1926  * which is called by gtk_init(). The program name is found by taking 
1927  * the last component of <literal>argv[0]</literal>.)
1928  *
1929  * Returns: the name of the program. The returned string belongs 
1930  * to GLib and must not be modified or freed.
1931  */
1932 gchar*
1933 g_get_prgname (void)
1934 {
1935   gchar* retval;
1936
1937   G_LOCK (g_prgname);
1938 #ifdef G_OS_WIN32
1939   if (g_prgname == NULL)
1940     {
1941       static gboolean beenhere = FALSE;
1942
1943       if (!beenhere)
1944         {
1945           gchar *utf8_buf = NULL;
1946           wchar_t buf[MAX_PATH+1];
1947
1948           beenhere = TRUE;
1949           if (GetModuleFileNameW (GetModuleHandle (NULL),
1950                                   buf, G_N_ELEMENTS (buf)) > 0)
1951             utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1952
1953           if (utf8_buf)
1954             {
1955               g_prgname = g_path_get_basename (utf8_buf);
1956               g_free (utf8_buf);
1957             }
1958         }
1959     }
1960 #endif
1961   retval = g_prgname;
1962   G_UNLOCK (g_prgname);
1963
1964   return retval;
1965 }
1966
1967 /**
1968  * g_set_prgname:
1969  * @prgname: the name of the program.
1970  *
1971  * Sets the name of the program. This name should <emphasis>not</emphasis> 
1972  * be localized, contrast with g_set_application_name(). Note that for 
1973  * thread-safety reasons this function can only be called once.
1974  */
1975 void
1976 g_set_prgname (const gchar *prgname)
1977 {
1978   G_LOCK (g_prgname);
1979   g_free (g_prgname);
1980   g_prgname = g_strdup (prgname);
1981   G_UNLOCK (g_prgname);
1982 }
1983
1984 G_LOCK_DEFINE_STATIC (g_application_name);
1985 static gchar *g_application_name = NULL;
1986
1987 /**
1988  * g_get_application_name:
1989  * 
1990  * Gets a human-readable name for the application, as set by
1991  * g_set_application_name(). This name should be localized if
1992  * possible, and is intended for display to the user.  Contrast with
1993  * g_get_prgname(), which gets a non-localized name. If
1994  * g_set_application_name() has not been called, returns the result of
1995  * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1996  * been called).
1997  * 
1998  * Return value: human-readable application name. may return %NULL
1999  *
2000  * Since: 2.2
2001  **/
2002 G_CONST_RETURN gchar*
2003 g_get_application_name (void)
2004 {
2005   gchar* retval;
2006
2007   G_LOCK (g_application_name);
2008   retval = g_application_name;
2009   G_UNLOCK (g_application_name);
2010
2011   if (retval == NULL)
2012     return g_get_prgname ();
2013   
2014   return retval;
2015 }
2016
2017 /**
2018  * g_set_application_name:
2019  * @application_name: localized name of the application
2020  *
2021  * Sets a human-readable name for the application. This name should be
2022  * localized if possible, and is intended for display to the user.
2023  * Contrast with g_set_prgname(), which sets a non-localized name.
2024  * g_set_prgname() will be called automatically by gtk_init(),
2025  * but g_set_application_name() will not.
2026  *
2027  * Note that for thread safety reasons, this function can only
2028  * be called once.
2029  *
2030  * The application name will be used in contexts such as error messages,
2031  * or when displaying an application's name in the task list.
2032  * 
2033  * Since: 2.2
2034  **/
2035 void
2036 g_set_application_name (const gchar *application_name)
2037 {
2038   gboolean already_set = FALSE;
2039         
2040   G_LOCK (g_application_name);
2041   if (g_application_name)
2042     already_set = TRUE;
2043   else
2044     g_application_name = g_strdup (application_name);
2045   G_UNLOCK (g_application_name);
2046
2047   if (already_set)
2048     g_warning ("g_set_application_name() called multiple times");
2049 }
2050
2051 /**
2052  * g_get_user_data_dir:
2053  * 
2054  * Returns a base directory in which to access application data such
2055  * as icons that is customized for a particular user.  
2056  *
2057  * On UNIX platforms this is determined using the mechanisms described in
2058  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2059  * XDG Base Directory Specification</ulink>.
2060  * In this case the directory retrieved will be XDG_DATA_HOME.
2061  *
2062  * On Windows is the virtual folder that represents the My Documents
2063  * desktop item. See documentation for CSIDL_PERSONAL.
2064  *
2065  * Return value: a string owned by GLib that must not be modified 
2066  *               or freed.
2067  * Since: 2.6
2068  **/
2069 G_CONST_RETURN gchar*
2070 g_get_user_data_dir (void)
2071 {
2072   gchar *data_dir;  
2073
2074   G_LOCK (g_utils_global);
2075
2076   if (!g_user_data_dir)
2077     {
2078 #ifdef G_OS_WIN32
2079       data_dir = get_special_folder (CSIDL_PERSONAL);
2080 #else
2081       data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2082
2083       if (data_dir && data_dir[0])
2084         data_dir = g_strdup (data_dir);
2085 #endif
2086       if (!data_dir || !data_dir[0])
2087         {
2088           g_get_any_init ();
2089
2090           if (g_home_dir)
2091             data_dir = g_build_filename (g_home_dir, ".local", 
2092                                          "share", NULL);
2093           else
2094             data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local", 
2095                                          "share", NULL);
2096         }
2097
2098       g_user_data_dir = data_dir;
2099     }
2100   else
2101     data_dir = g_user_data_dir;
2102
2103   G_UNLOCK (g_utils_global);
2104
2105   return data_dir;
2106 }
2107
2108 static void
2109 g_init_user_config_dir (void)
2110 {
2111   gchar *config_dir;
2112
2113   if (!g_user_config_dir)
2114     {
2115 #ifdef G_OS_WIN32
2116       config_dir = get_special_folder (CSIDL_APPDATA);
2117 #else
2118       config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2119
2120       if (config_dir && config_dir[0])
2121         config_dir = g_strdup (config_dir);
2122 #endif
2123       if (!config_dir || !config_dir[0])
2124         {
2125           g_get_any_init ();
2126
2127           if (g_home_dir)
2128             config_dir = g_build_filename (g_home_dir, ".config", NULL);
2129           else
2130             config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2131         }
2132
2133       g_user_config_dir = config_dir;
2134     }
2135 }
2136
2137 /**
2138  * g_get_user_config_dir:
2139  * 
2140  * Returns a base directory in which to store user-specific application 
2141  * configuration information such as user preferences and settings. 
2142  *
2143  * On UNIX platforms this is determined using the mechanisms described in
2144  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2145  * XDG Base Directory Specification</ulink>.
2146  * In this case the directory retrieved will be XDG_CONFIG_HOME.
2147  *
2148  * On Windows is the directory that serves as a common repository for
2149  * application-specific data. A typical path is
2150  * C:\Documents and Settings\username\Application. See documentation for
2151  * CSIDL_APPDATA.
2152  *
2153  * Return value: a string owned by GLib that must not be modified 
2154  *               or freed.
2155  * Since: 2.6
2156  **/
2157 G_CONST_RETURN gchar*
2158 g_get_user_config_dir (void)
2159 {
2160   G_LOCK (g_utils_global);
2161
2162   g_init_user_config_dir ();
2163
2164   G_UNLOCK (g_utils_global);
2165
2166   return g_user_config_dir;
2167 }
2168
2169 /**
2170  * g_get_user_cache_dir:
2171  * 
2172  * Returns a base directory in which to store non-essential, cached
2173  * data specific to particular user.
2174  *
2175  * On UNIX platforms this is determined using the mechanisms described in
2176  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2177  * XDG Base Directory Specification</ulink>.
2178  * In this case the directory retrieved will be XDG_CACHE_HOME.
2179  *
2180  * On Windows is the directory that serves as a common repository for
2181  * temporary Internet files. A typical path is
2182  * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
2183  * See documentation for CSIDL_INTERNET_CACHE.
2184  *
2185  * Return value: a string owned by GLib that must not be modified 
2186  *               or freed.
2187  * Since: 2.6
2188  **/
2189 G_CONST_RETURN gchar*
2190 g_get_user_cache_dir (void)
2191 {
2192   gchar *cache_dir;  
2193
2194   G_LOCK (g_utils_global);
2195
2196   if (!g_user_cache_dir)
2197     {
2198 #ifdef G_OS_WIN32
2199       cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2200 #else
2201       cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2202
2203       if (cache_dir && cache_dir[0])
2204           cache_dir = g_strdup (cache_dir);
2205 #endif
2206       if (!cache_dir || !cache_dir[0])
2207         {
2208           g_get_any_init ();
2209         
2210           if (g_home_dir)
2211             cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2212           else
2213             cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2214         }
2215       g_user_cache_dir = cache_dir;
2216     }
2217   else
2218     cache_dir = g_user_cache_dir;
2219
2220   G_UNLOCK (g_utils_global);
2221
2222   return cache_dir;
2223 }
2224
2225 #ifdef HAVE_CARBON
2226
2227 static gchar *
2228 find_folder (OSType type)
2229 {
2230   gchar *filename = NULL;
2231   FSRef  found;
2232
2233   if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2234     {
2235       CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2236
2237       if (url)
2238         {
2239           CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2240
2241           if (path)
2242             {
2243               filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2244
2245               if (! filename)
2246                 {
2247                   filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2248
2249                   CFStringGetCString (path, filename,
2250                                       CFStringGetLength (path) * 3 + 1,
2251                                       kCFStringEncodingUTF8);
2252                 }
2253
2254               CFRelease (path);
2255             }
2256
2257           CFRelease (url);
2258         }
2259     }
2260
2261   return filename;
2262 }
2263
2264 static void
2265 load_user_special_dirs (void)
2266 {
2267   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2268   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2269   g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2270   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2271   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2272   g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2273   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2274   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2275 }
2276
2277 #endif /* HAVE_CARBON */
2278
2279 #if defined(G_OS_WIN32)
2280 static void
2281 load_user_special_dirs (void)
2282 {
2283   typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2284                                                     DWORD dwFlags,
2285                                                     HANDLE hToken,
2286                                                     PWSTR *ppszPath);
2287   t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2288
2289   static const GUID FOLDERID_Downloads =
2290     { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2291   static const GUID FOLDERID_Public =
2292     { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2293
2294   wchar_t *wcp;
2295
2296   p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
2297                                                                     "SHGetKnownFolderPath");
2298
2299   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2300   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2301
2302   if (p_SHGetKnownFolderPath == NULL)
2303     {
2304       g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2305     }
2306   else
2307     {
2308       wcp = NULL;
2309       (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2310       g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2311       if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2312         g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2313       CoTaskMemFree (wcp);
2314     }
2315
2316   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2317   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2318
2319   if (p_SHGetKnownFolderPath == NULL)
2320     {
2321       /* XXX */
2322       g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2323     }
2324   else
2325     {
2326       wcp = NULL;
2327       (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2328       g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2329       if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2330         g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2331       CoTaskMemFree (wcp);
2332     }
2333   
2334   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2335   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2336 }
2337 #endif /* G_OS_WIN32 */
2338
2339 static void g_init_user_config_dir (void);
2340
2341 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2342
2343 /* adapted from xdg-user-dir-lookup.c
2344  *
2345  * Copyright (C) 2007 Red Hat Inc.
2346  *
2347  * Permission is hereby granted, free of charge, to any person
2348  * obtaining a copy of this software and associated documentation files
2349  * (the "Software"), to deal in the Software without restriction,
2350  * including without limitation the rights to use, copy, modify, merge,
2351  * publish, distribute, sublicense, and/or sell copies of the Software,
2352  * and to permit persons to whom the Software is furnished to do so,
2353  * subject to the following conditions: 
2354  *
2355  * The above copyright notice and this permission notice shall be
2356  * included in all copies or substantial portions of the Software. 
2357  *
2358  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2359  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2360  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2361  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2362  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2363  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2364  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2365  * SOFTWARE.
2366  */
2367 static void
2368 load_user_special_dirs (void)
2369 {
2370   gchar *config_file;
2371   gchar *data;
2372   gchar **lines;
2373   gint n_lines, i;
2374   
2375   g_init_user_config_dir ();
2376   config_file = g_build_filename (g_user_config_dir,
2377                                   "user-dirs.dirs",
2378                                   NULL);
2379   
2380   if (!g_file_get_contents (config_file, &data, NULL, NULL))
2381     {
2382       g_free (config_file);
2383       return;
2384     }
2385
2386   lines = g_strsplit (data, "\n", -1);
2387   n_lines = g_strv_length (lines);
2388   g_free (data);
2389   
2390   for (i = 0; i < n_lines; i++)
2391     {
2392       gchar *buffer = lines[i];
2393       gchar *d, *p;
2394       gint len;
2395       gboolean is_relative = FALSE;
2396       GUserDirectory directory;
2397
2398       /* Remove newline at end */
2399       len = strlen (buffer);
2400       if (len > 0 && buffer[len - 1] == '\n')
2401         buffer[len - 1] = 0;
2402       
2403       p = buffer;
2404       while (*p == ' ' || *p == '\t')
2405         p++;
2406       
2407       if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2408         {
2409           directory = G_USER_DIRECTORY_DESKTOP;
2410           p += strlen ("XDG_DESKTOP_DIR");
2411         }
2412       else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2413         {
2414           directory = G_USER_DIRECTORY_DOCUMENTS;
2415           p += strlen ("XDG_DOCUMENTS_DIR");
2416         }
2417       else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2418         {
2419           directory = G_USER_DIRECTORY_DOWNLOAD;
2420           p += strlen ("XDG_DOWNLOAD_DIR");
2421         }
2422       else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2423         {
2424           directory = G_USER_DIRECTORY_MUSIC;
2425           p += strlen ("XDG_MUSIC_DIR");
2426         }
2427       else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2428         {
2429           directory = G_USER_DIRECTORY_PICTURES;
2430           p += strlen ("XDG_PICTURES_DIR");
2431         }
2432       else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2433         {
2434           directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2435           p += strlen ("XDG_PUBLICSHARE_DIR");
2436         }
2437       else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2438         {
2439           directory = G_USER_DIRECTORY_TEMPLATES;
2440           p += strlen ("XDG_TEMPLATES_DIR");
2441         }
2442       else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2443         {
2444           directory = G_USER_DIRECTORY_VIDEOS;
2445           p += strlen ("XDG_VIDEOS_DIR");
2446         }
2447       else
2448         continue;
2449
2450       while (*p == ' ' || *p == '\t')
2451         p++;
2452
2453       if (*p != '=')
2454         continue;
2455       p++;
2456
2457       while (*p == ' ' || *p == '\t')
2458         p++;
2459
2460       if (*p != '"')
2461         continue;
2462       p++;
2463
2464       if (strncmp (p, "$HOME", 5) == 0)
2465         {
2466           p += 5;
2467           is_relative = TRUE;
2468         }
2469       else if (*p != '/')
2470         continue;
2471
2472       d = strrchr (p, '"');
2473       if (!d)
2474         continue;
2475       *d = 0;
2476
2477       d = p;
2478       
2479       /* remove trailing slashes */
2480       len = strlen (d);
2481       if (d[len - 1] == '/')
2482         d[len - 1] = 0;
2483       
2484       if (is_relative)
2485         {
2486           g_get_any_init ();
2487           g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2488         }
2489       else
2490         g_user_special_dirs[directory] = g_strdup (d);
2491     }
2492
2493   g_strfreev (lines);
2494   g_free (config_file);
2495 }
2496
2497 #endif /* G_OS_UNIX && !HAVE_CARBON */
2498
2499
2500 /**
2501  * g_reload_user_special_dirs_cache:
2502  *
2503  * Resets the cache used for g_get_user_special_dir(), so
2504  * that the latest on-disk version is used. Call this only
2505  * if you just changed the data on disk yourself.
2506  *
2507  * Due to threadsafety issues this may cause leaking of strings
2508  * that were previously returned from g_get_user_special_dir()
2509  * that can't be freed. We ensure to only leak the data for
2510  * the directories that actually changed value though.
2511  *
2512  * Since: 2.22
2513  */
2514 void
2515 g_reload_user_special_dirs_cache (void)
2516 {
2517   int i;
2518
2519   G_LOCK (g_utils_global);
2520
2521   if (g_user_special_dirs != NULL)
2522     {
2523       /* save a copy of the pointer, to check if some memory can be preserved */
2524       char **old_g_user_special_dirs = g_user_special_dirs;
2525       char *old_val;
2526
2527       /* recreate and reload our cache */
2528       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2529       load_user_special_dirs ();
2530
2531       /* only leak changed directories */
2532       for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2533         {
2534           old_val = old_g_user_special_dirs[i];
2535           if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2536             {
2537               /* don't leak */
2538               g_free (g_user_special_dirs[i]);
2539               g_user_special_dirs[i] = old_val;
2540             }
2541           else
2542             g_free (old_val);
2543         }
2544
2545       /* free the old array */
2546       g_free (old_g_user_special_dirs);
2547     }
2548
2549   G_UNLOCK (g_utils_global);
2550 }
2551
2552 /**
2553  * g_get_user_special_dir:
2554  * @directory: the logical id of special directory
2555  *
2556  * Returns the full path of a special directory using its logical id.
2557  *
2558  * On Unix this is done using the XDG special user directories.
2559  * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2560  * falls back to <filename>$HOME/Desktop</filename> when XDG special
2561  * user directories have not been set up. 
2562  *
2563  * Depending on the platform, the user might be able to change the path
2564  * of the special directory without requiring the session to restart; GLib
2565  * will not reflect any change once the special directories are loaded.
2566  *
2567  * Return value: the path to the specified special directory, or %NULL
2568  *   if the logical id was not found. The returned string is owned by
2569  *   GLib and should not be modified or freed.
2570  *
2571  * Since: 2.14
2572  */
2573 G_CONST_RETURN gchar *
2574 g_get_user_special_dir (GUserDirectory directory)
2575 {
2576   g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2577                         directory < G_USER_N_DIRECTORIES, NULL);
2578
2579   G_LOCK (g_utils_global);
2580
2581   if (G_UNLIKELY (g_user_special_dirs == NULL))
2582     {
2583       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2584
2585       load_user_special_dirs ();
2586
2587       /* Special-case desktop for historical compatibility */
2588       if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2589         {
2590           g_get_any_init ();
2591
2592           g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2593             g_build_filename (g_home_dir, "Desktop", NULL);
2594         }
2595     }
2596
2597   G_UNLOCK (g_utils_global);
2598
2599   return g_user_special_dirs[directory];
2600 }
2601
2602 #ifdef G_OS_WIN32
2603
2604 #undef g_get_system_data_dirs
2605
2606 static HMODULE
2607 get_module_for_address (gconstpointer address)
2608 {
2609   /* Holds the g_utils_global lock */
2610
2611   static gboolean beenhere = FALSE;
2612   typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2613   static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2614   HMODULE hmodule = NULL;
2615
2616   if (!address)
2617     return NULL;
2618
2619   if (!beenhere)
2620     {
2621       p_GetModuleHandleExA =
2622         (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2623                                                "GetModuleHandleExA");
2624       beenhere = TRUE;
2625     }
2626
2627   if (p_GetModuleHandleExA == NULL ||
2628       !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2629                                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2630                                 address, &hmodule))
2631     {
2632       MEMORY_BASIC_INFORMATION mbi;
2633       VirtualQuery (address, &mbi, sizeof (mbi));
2634       hmodule = (HMODULE) mbi.AllocationBase;
2635     }
2636
2637   return hmodule;
2638 }
2639
2640 static gchar *
2641 get_module_share_dir (gconstpointer address)
2642 {
2643   HMODULE hmodule;
2644   gchar *filename;
2645   gchar *retval;
2646
2647   hmodule = get_module_for_address (address);
2648   if (hmodule == NULL)
2649     return NULL;
2650
2651   filename = g_win32_get_package_installation_directory_of_module (hmodule);
2652   retval = g_build_filename (filename, "share", NULL);
2653   g_free (filename);
2654
2655   return retval;
2656 }
2657
2658 G_CONST_RETURN gchar * G_CONST_RETURN *
2659 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2660 {
2661   GArray *data_dirs;
2662   HMODULE hmodule;
2663   static GHashTable *per_module_data_dirs = NULL;
2664   gchar **retval;
2665   gchar *p;
2666   gchar *exe_root;
2667       
2668   if (address_of_function)
2669     {
2670       G_LOCK (g_utils_global);
2671       hmodule = get_module_for_address (address_of_function);
2672       if (hmodule != NULL)
2673         {
2674           if (per_module_data_dirs == NULL)
2675             per_module_data_dirs = g_hash_table_new (NULL, NULL);
2676           else
2677             {
2678               retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2679               
2680               if (retval != NULL)
2681                 {
2682                   G_UNLOCK (g_utils_global);
2683                   return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2684                 }
2685             }
2686         }
2687     }
2688
2689   data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2690
2691   /* Documents and Settings\All Users\Application Data */
2692   p = get_special_folder (CSIDL_COMMON_APPDATA);
2693   if (p)
2694     g_array_append_val (data_dirs, p);
2695   
2696   /* Documents and Settings\All Users\Documents */
2697   p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2698   if (p)
2699     g_array_append_val (data_dirs, p);
2700         
2701   /* Using the above subfolders of Documents and Settings perhaps
2702    * makes sense from a Windows perspective.
2703    *
2704    * But looking at the actual use cases of this function in GTK+
2705    * and GNOME software, what we really want is the "share"
2706    * subdirectory of the installation directory for the package
2707    * our caller is a part of.
2708    *
2709    * The address_of_function parameter, if non-NULL, points to a
2710    * function in the calling module. Use that to determine that
2711    * module's installation folder, and use its "share" subfolder.
2712    *
2713    * Additionally, also use the "share" subfolder of the installation
2714    * locations of GLib and the .exe file being run.
2715    *
2716    * To guard against none of the above being what is really wanted,
2717    * callers of this function should have Win32-specific code to look
2718    * up their installation folder themselves, and handle a subfolder
2719    * "share" of it in the same way as the folders returned from this
2720    * function.
2721    */
2722
2723   p = get_module_share_dir (address_of_function);
2724   if (p)
2725     g_array_append_val (data_dirs, p);
2726     
2727   if (glib_dll != NULL)
2728     {
2729       gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2730       p = g_build_filename (glib_root, "share", NULL);
2731       if (p)
2732         g_array_append_val (data_dirs, p);
2733       g_free (glib_root);
2734     }
2735   
2736   exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2737   p = g_build_filename (exe_root, "share", NULL);
2738   if (p)
2739     g_array_append_val (data_dirs, p);
2740   g_free (exe_root);
2741
2742   retval = (gchar **) g_array_free (data_dirs, FALSE);
2743
2744   if (address_of_function)
2745     {
2746       if (hmodule != NULL)
2747         g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2748       G_UNLOCK (g_utils_global);
2749     }
2750
2751   return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2752 }
2753
2754 #endif
2755
2756 /**
2757  * g_get_system_data_dirs:
2758  * 
2759  * Returns an ordered list of base directories in which to access 
2760  * system-wide application data.
2761  *
2762  * On UNIX platforms this is determined using the mechanisms described in
2763  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2764  * XDG Base Directory Specification</ulink>
2765  * In this case the list of directories retrieved will be XDG_DATA_DIRS.
2766  *
2767  * On Windows the first elements in the list are the Application Data
2768  * and Documents folders for All Users. (These can be determined only
2769  * on Windows 2000 or later and are not present in the list on other
2770  * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2771  * CSIDL_COMMON_DOCUMENTS.
2772  *
2773  * Then follows the "share" subfolder in the installation folder for
2774  * the package containing the DLL that calls this function, if it can
2775  * be determined.
2776  * 
2777  * Finally the list contains the "share" subfolder in the installation
2778  * folder for GLib, and in the installation folder for the package the
2779  * application's .exe file belongs to.
2780  *
2781  * The installation folders above are determined by looking up the
2782  * folder where the module (DLL or EXE) in question is located. If the
2783  * folder's name is "bin", its parent is used, otherwise the folder
2784  * itself.
2785  *
2786  * Note that on Windows the returned list can vary depending on where
2787  * this function is called.
2788  *
2789  * Return value: a %NULL-terminated array of strings owned by GLib that must 
2790  *               not be modified or freed.
2791  * Since: 2.6
2792  **/
2793 G_CONST_RETURN gchar * G_CONST_RETURN * 
2794 g_get_system_data_dirs (void)
2795 {
2796   gchar **data_dir_vector;
2797
2798   G_LOCK (g_utils_global);
2799
2800   if (!g_system_data_dirs)
2801     {
2802 #ifdef G_OS_WIN32
2803       data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2804 #else
2805       gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2806
2807       if (!data_dirs || !data_dirs[0])
2808           data_dirs = "/usr/local/share/:/usr/share/";
2809
2810       data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2811 #endif
2812
2813       g_system_data_dirs = data_dir_vector;
2814     }
2815   else
2816     data_dir_vector = g_system_data_dirs;
2817
2818   G_UNLOCK (g_utils_global);
2819
2820   return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2821 }
2822
2823 /**
2824  * g_get_system_config_dirs:
2825  * 
2826  * Returns an ordered list of base directories in which to access 
2827  * system-wide configuration information.
2828  *
2829  * On UNIX platforms this is determined using the mechanisms described in
2830  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2831  * XDG Base Directory Specification</ulink>.
2832  * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2833  *
2834  * On Windows is the directory that contains application data for all users.
2835  * A typical path is C:\Documents and Settings\All Users\Application Data.
2836  * This folder is used for application data that is not user specific.
2837  * For example, an application can store a spell-check dictionary, a database
2838  * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2839  * This information will not roam and is available to anyone using the computer.
2840  *
2841  * Return value: a %NULL-terminated array of strings owned by GLib that must 
2842  *               not be modified or freed.
2843  * Since: 2.6
2844  **/
2845 G_CONST_RETURN gchar * G_CONST_RETURN *
2846 g_get_system_config_dirs (void)
2847 {
2848   gchar *conf_dirs, **conf_dir_vector;
2849
2850   G_LOCK (g_utils_global);
2851
2852   if (!g_system_config_dirs)
2853     {
2854 #ifdef G_OS_WIN32
2855       conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2856       if (conf_dirs)
2857         {
2858           conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2859           g_free (conf_dirs);
2860         }
2861       else
2862         {
2863           /* Return empty list */
2864           conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2865         }
2866 #else
2867       conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2868
2869       if (!conf_dirs || !conf_dirs[0])
2870           conf_dirs = "/etc/xdg";
2871
2872       conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2873 #endif
2874
2875       g_system_config_dirs = conf_dir_vector;
2876     }
2877   else
2878     conf_dir_vector = g_system_config_dirs;
2879   G_UNLOCK (g_utils_global);
2880
2881   return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2882 }
2883
2884 #ifndef G_OS_WIN32
2885
2886 static GHashTable *alias_table = NULL;
2887
2888 /* read an alias file for the locales */
2889 static void
2890 read_aliases (gchar *file)
2891 {
2892   FILE *fp;
2893   char buf[256];
2894   
2895   if (!alias_table)
2896     alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2897   fp = fopen (file,"r");
2898   if (!fp)
2899     return;
2900   while (fgets (buf, 256, fp))
2901     {
2902       char *p, *q;
2903
2904       g_strstrip (buf);
2905
2906       /* Line is a comment */
2907       if ((buf[0] == '#') || (buf[0] == '\0'))
2908         continue;
2909
2910       /* Reads first column */
2911       for (p = buf, q = NULL; *p; p++) {
2912         if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2913           *p = '\0';
2914           q = p+1;
2915           while ((*q == '\t') || (*q == ' ')) {
2916             q++;
2917           }
2918           break;
2919         }
2920       }
2921       /* The line only had one column */
2922       if (!q || *q == '\0')
2923         continue;
2924       
2925       /* Read second column */
2926       for (p = q; *p; p++) {
2927         if ((*p == '\t') || (*p == ' ')) {
2928           *p = '\0';
2929           break;
2930         }
2931       }
2932
2933       /* Add to alias table if necessary */
2934       if (!g_hash_table_lookup (alias_table, buf)) {
2935         g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2936       }
2937     }
2938   fclose (fp);
2939 }
2940
2941 #endif
2942
2943 static char *
2944 unalias_lang (char *lang)
2945 {
2946 #ifndef G_OS_WIN32
2947   char *p;
2948   int i;
2949
2950   if (!alias_table)
2951     read_aliases ("/usr/share/locale/locale.alias");
2952
2953   i = 0;
2954   while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2955     {
2956       lang = p;
2957       if (i++ == 30)
2958         {
2959           static gboolean said_before = FALSE;
2960           if (!said_before)
2961             g_warning ("Too many alias levels for a locale, "
2962                        "may indicate a loop");
2963           said_before = TRUE;
2964           return lang;
2965         }
2966     }
2967 #endif
2968   return lang;
2969 }
2970
2971 /* Mask for components of locale spec. The ordering here is from
2972  * least significant to most significant
2973  */
2974 enum
2975 {
2976   COMPONENT_CODESET =   1 << 0,
2977   COMPONENT_TERRITORY = 1 << 1,
2978   COMPONENT_MODIFIER =  1 << 2
2979 };
2980
2981 /* Break an X/Open style locale specification into components
2982  */
2983 static guint
2984 explode_locale (const gchar *locale,
2985                 gchar      **language, 
2986                 gchar      **territory, 
2987                 gchar      **codeset, 
2988                 gchar      **modifier)
2989 {
2990   const gchar *uscore_pos;
2991   const gchar *at_pos;
2992   const gchar *dot_pos;
2993
2994   guint mask = 0;
2995
2996   uscore_pos = strchr (locale, '_');
2997   dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2998   at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2999
3000   if (at_pos)
3001     {
3002       mask |= COMPONENT_MODIFIER;
3003       *modifier = g_strdup (at_pos);
3004     }
3005   else
3006     at_pos = locale + strlen (locale);
3007
3008   if (dot_pos)
3009     {
3010       mask |= COMPONENT_CODESET;
3011       *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3012     }
3013   else
3014     dot_pos = at_pos;
3015
3016   if (uscore_pos)
3017     {
3018       mask |= COMPONENT_TERRITORY;
3019       *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3020     }
3021   else
3022     uscore_pos = dot_pos;
3023
3024   *language = g_strndup (locale, uscore_pos - locale);
3025
3026   return mask;
3027 }
3028
3029 /*
3030  * Compute all interesting variants for a given locale name -
3031  * by stripping off different components of the value.
3032  *
3033  * For simplicity, we assume that the locale is in
3034  * X/Open format: language[_territory][.codeset][@modifier]
3035  *
3036  * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3037  *       as well. We could just copy the code from glibc wholesale
3038  *       but it is big, ugly, and complicated, so I'm reluctant
3039  *       to do so when this should handle 99% of the time...
3040  */
3041 GSList *
3042 _g_compute_locale_variants (const gchar *locale)
3043 {
3044   GSList *retval = NULL;
3045
3046   gchar *language = NULL;
3047   gchar *territory = NULL;
3048   gchar *codeset = NULL;
3049   gchar *modifier = NULL;
3050
3051   guint mask;
3052   guint i;
3053
3054   g_return_val_if_fail (locale != NULL, NULL);
3055
3056   mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3057
3058   /* Iterate through all possible combinations, from least attractive
3059    * to most attractive.
3060    */
3061   for (i = 0; i <= mask; i++)
3062     if ((i & ~mask) == 0)
3063       {
3064         gchar *val = g_strconcat (language,
3065                                   (i & COMPONENT_TERRITORY) ? territory : "",
3066                                   (i & COMPONENT_CODESET) ? codeset : "",
3067                                   (i & COMPONENT_MODIFIER) ? modifier : "",
3068                                   NULL);
3069         retval = g_slist_prepend (retval, val);
3070       }
3071
3072   g_free (language);
3073   if (mask & COMPONENT_CODESET)
3074     g_free (codeset);
3075   if (mask & COMPONENT_TERRITORY)
3076     g_free (territory);
3077   if (mask & COMPONENT_MODIFIER)
3078     g_free (modifier);
3079
3080   return retval;
3081 }
3082
3083 /* The following is (partly) taken from the gettext package.
3084    Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc.  */
3085
3086 static const gchar *
3087 guess_category_value (const gchar *category_name)
3088 {
3089   const gchar *retval;
3090
3091   /* The highest priority value is the `LANGUAGE' environment
3092      variable.  This is a GNU extension.  */
3093   retval = g_getenv ("LANGUAGE");
3094   if ((retval != NULL) && (retval[0] != '\0'))
3095     return retval;
3096
3097   /* `LANGUAGE' is not set.  So we have to proceed with the POSIX
3098      methods of looking to `LC_ALL', `LC_xxx', and `LANG'.  On some
3099      systems this can be done by the `setlocale' function itself.  */
3100
3101   /* Setting of LC_ALL overwrites all other.  */
3102   retval = g_getenv ("LC_ALL");  
3103   if ((retval != NULL) && (retval[0] != '\0'))
3104     return retval;
3105
3106   /* Next comes the name of the desired category.  */
3107   retval = g_getenv (category_name);
3108   if ((retval != NULL) && (retval[0] != '\0'))
3109     return retval;
3110
3111   /* Last possibility is the LANG environment variable.  */
3112   retval = g_getenv ("LANG");
3113   if ((retval != NULL) && (retval[0] != '\0'))
3114     return retval;
3115
3116 #ifdef G_PLATFORM_WIN32
3117   /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3118    * LANG, which we already did above. Oh well. The main point of
3119    * calling g_win32_getlocale() is to get the thread's locale as used
3120    * by Windows and the Microsoft C runtime (in the "English_United
3121    * States" format) translated into the Unixish format.
3122    */
3123   {
3124     char *locale = g_win32_getlocale ();
3125     retval = g_intern_string (locale);
3126     g_free (locale);
3127     return retval;
3128   }
3129 #endif  
3130
3131   return NULL;
3132 }
3133
3134 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3135
3136 struct _GLanguageNamesCache {
3137   gchar *languages;
3138   gchar **language_names;
3139 };
3140
3141 static void
3142 language_names_cache_free (gpointer data)
3143 {
3144   GLanguageNamesCache *cache = data;
3145   g_free (cache->languages);
3146   g_strfreev (cache->language_names);
3147   g_free (cache);
3148 }
3149
3150 /**
3151  * g_get_language_names:
3152  * 
3153  * Computes a list of applicable locale names, which can be used to 
3154  * e.g. construct locale-dependent filenames or search paths. The returned 
3155  * list is sorted from most desirable to least desirable and always contains 
3156  * the default locale "C".
3157  *
3158  * For example, if LANGUAGE=de:en_US, then the returned list is
3159  * "de", "en_US", "en", "C".
3160  *
3161  * This function consults the environment variables <envar>LANGUAGE</envar>, 
3162  * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar> 
3163  * to find the list of locales specified by the user.
3164  * 
3165  * Return value: a %NULL-terminated array of strings owned by GLib 
3166  *    that must not be modified or freed.
3167  *
3168  * Since: 2.6
3169  **/
3170 G_CONST_RETURN gchar * G_CONST_RETURN * 
3171 g_get_language_names (void)
3172 {
3173   static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3174   GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3175   const gchar *value;
3176
3177   if (!cache)
3178     {
3179       cache = g_new0 (GLanguageNamesCache, 1);
3180       g_static_private_set (&cache_private, cache, language_names_cache_free);
3181     }
3182
3183   value = guess_category_value ("LC_MESSAGES");
3184   if (!value)
3185     value = "C";
3186
3187   if (!(cache->languages && strcmp (cache->languages, value) == 0))
3188     {
3189       gchar **languages;
3190       gchar **alist, **a;
3191       GSList *list, *l;
3192       gint i;
3193
3194       g_free (cache->languages);
3195       g_strfreev (cache->language_names);
3196       cache->languages = g_strdup (value);
3197
3198       alist = g_strsplit (value, ":", 0);
3199       list = NULL;
3200       for (a = alist; *a; a++)
3201         {
3202           gchar *b = unalias_lang (*a);
3203           list = g_slist_concat (list, _g_compute_locale_variants (b));
3204         }
3205       g_strfreev (alist);
3206       list = g_slist_append (list, g_strdup ("C"));
3207
3208       cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
3209       for (l = list, i = 0; l; l = l->next, i++)
3210         languages[i] = l->data;
3211       languages[i] = NULL;
3212
3213       g_slist_free (list);
3214     }
3215
3216   return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3217 }
3218
3219 /**
3220  * g_direct_hash:
3221  * @v: a #gpointer key
3222  *
3223  * Converts a gpointer to a hash value.
3224  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
3225  * when using pointers as keys in a #GHashTable.
3226  *
3227  * Returns: a hash value corresponding to the key.
3228  */
3229 guint
3230 g_direct_hash (gconstpointer v)
3231 {
3232   return GPOINTER_TO_UINT (v);
3233 }
3234
3235 /**
3236  * g_direct_equal:
3237  * @v1: a key.
3238  * @v2: a key to compare with @v1.
3239  *
3240  * Compares two #gpointer arguments and returns %TRUE if they are equal.
3241  * It can be passed to g_hash_table_new() as the @key_equal_func
3242  * parameter, when using pointers as keys in a #GHashTable.
3243  * 
3244  * Returns: %TRUE if the two keys match.
3245  */
3246 gboolean
3247 g_direct_equal (gconstpointer v1,
3248                 gconstpointer v2)
3249 {
3250   return v1 == v2;
3251 }
3252
3253 /**
3254  * g_int_equal:
3255  * @v1: a pointer to a #gint key.
3256  * @v2: a pointer to a #gint key to compare with @v1.
3257  *
3258  * Compares the two #gint values being pointed to and returns 
3259  * %TRUE if they are equal.
3260  * It can be passed to g_hash_table_new() as the @key_equal_func
3261  * parameter, when using pointers to integers as keys in a #GHashTable.
3262  * 
3263  * Returns: %TRUE if the two keys match.
3264  */
3265 gboolean
3266 g_int_equal (gconstpointer v1,
3267              gconstpointer v2)
3268 {
3269   return *((const gint*) v1) == *((const gint*) v2);
3270 }
3271
3272 /**
3273  * g_int_hash:
3274  * @v: a pointer to a #gint key
3275  *
3276  * Converts a pointer to a #gint to a hash value.
3277  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
3278  * when using pointers to integers values as keys in a #GHashTable.
3279  *
3280  * Returns: a hash value corresponding to the key.
3281  */
3282 guint
3283 g_int_hash (gconstpointer v)
3284 {
3285   return *(const gint*) v;
3286 }
3287
3288 /**
3289  * g_int64_equal:
3290  * @v1: a pointer to a #gint64 key.
3291  * @v2: a pointer to a #gint64 key to compare with @v1.
3292  *
3293  * Compares the two #gint64 values being pointed to and returns 
3294  * %TRUE if they are equal.
3295  * It can be passed to g_hash_table_new() as the @key_equal_func
3296  * parameter, when using pointers to 64-bit integers as keys in a #GHashTable.
3297  * 
3298  * Returns: %TRUE if the two keys match.
3299  *
3300  * Since: 2.22
3301  */
3302 gboolean
3303 g_int64_equal (gconstpointer v1,
3304                gconstpointer v2)
3305 {
3306   return *((const gint64*) v1) == *((const gint64*) v2);
3307 }
3308
3309 /**
3310  * g_int64_hash:
3311  * @v: a pointer to a #gint64 key
3312  *
3313  * Converts a pointer to a #gint64 to a hash value.
3314  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
3315  * when using pointers to 64-bit integers values as keys in a #GHashTable.
3316  *
3317  * Returns: a hash value corresponding to the key.
3318  *
3319  * Since: 2.22
3320  */
3321 guint
3322 g_int64_hash (gconstpointer v)
3323 {
3324   return (guint) *(const gint64*) v;
3325 }
3326
3327 /**
3328  * g_double_equal:
3329  * @v1: a pointer to a #gdouble key.
3330  * @v2: a pointer to a #gdouble key to compare with @v1.
3331  *
3332  * Compares the two #gdouble values being pointed to and returns 
3333  * %TRUE if they are equal.
3334  * It can be passed to g_hash_table_new() as the @key_equal_func
3335  * parameter, when using pointers to doubles as keys in a #GHashTable.
3336  * 
3337  * Returns: %TRUE if the two keys match.
3338  *
3339  * Since: 2.22
3340  */
3341 gboolean
3342 g_double_equal (gconstpointer v1,
3343                 gconstpointer v2)
3344 {
3345   return *((const gdouble*) v1) == *((const gdouble*) v2);
3346 }
3347
3348 /**
3349  * g_double_hash:
3350  * @v: a pointer to a #gdouble key
3351  *
3352  * Converts a pointer to a #gdouble to a hash value.
3353  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
3354  * when using pointers to doubles as keys in a #GHashTable.
3355  *
3356  * Returns: a hash value corresponding to the key.
3357  *
3358  * Since: 2.22
3359  */
3360 guint
3361 g_double_hash (gconstpointer v)
3362 {
3363   return (guint) *(const gdouble*) v;
3364 }
3365
3366 /**
3367  * g_nullify_pointer:
3368  * @nullify_location: the memory address of the pointer.
3369  * 
3370  * Set the pointer at the specified location to %NULL.
3371  **/
3372 void
3373 g_nullify_pointer (gpointer *nullify_location)
3374 {
3375   g_return_if_fail (nullify_location != NULL);
3376
3377   *nullify_location = NULL;
3378 }
3379
3380 /**
3381  * g_get_codeset:
3382  * 
3383  * Get the codeset for the current locale.
3384  * 
3385  * Return value: a newly allocated string containing the name
3386  * of the codeset. This string must be freed with g_free().
3387  **/
3388 gchar *
3389 g_get_codeset (void)
3390 {
3391   const gchar *charset;
3392
3393   g_get_charset (&charset);
3394
3395   return g_strdup (charset);
3396 }
3397
3398 /* This is called from g_thread_init(). It's used to
3399  * initialize some static data in a threadsafe way.
3400  */
3401 void
3402 _g_utils_thread_init (void)
3403 {
3404   g_get_language_names ();
3405 }
3406
3407 #ifdef G_OS_WIN32
3408
3409 /**
3410  * _glib_get_locale_dir:
3411  *
3412  * Return the path to the share\locale or lib\locale subfolder of the
3413  * GLib installation folder. The path is in the system codepage. We
3414  * have to use system codepage as bindtextdomain() doesn't have a
3415  * UTF-8 interface.
3416  */
3417 static gchar *
3418 _glib_get_locale_dir (void)
3419 {
3420   gchar *install_dir = NULL, *locale_dir;
3421   gchar *retval = NULL;
3422
3423   if (glib_dll != NULL)
3424     install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3425
3426   if (install_dir)
3427     {
3428       /*
3429        * Append "/share/locale" or "/lib/locale" depending on whether
3430        * autoconfigury detected GNU gettext or not.
3431        */
3432       const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3433       while (*--p != '/')
3434         ;
3435       while (*--p != '/')
3436         ;
3437
3438       locale_dir = g_build_filename (install_dir, p, NULL);
3439
3440       retval = g_win32_locale_filename_from_utf8 (locale_dir);
3441
3442       g_free (install_dir);
3443       g_free (locale_dir);
3444     }
3445
3446   if (retval)
3447     return retval;
3448   else
3449     return g_strdup ("");
3450 }
3451
3452 #undef GLIB_LOCALE_DIR
3453
3454 #endif /* G_OS_WIN32 */
3455
3456 /**
3457  * glib_gettext:
3458  * @str: The string to be translated
3459  *
3460  * Returns the translated string from the glib translations.
3461  * This is an internal function and should only be used by
3462  * the internals of glib (such as libgio).
3463  *
3464  * Returns: the transation of @str to the current locale
3465  */
3466 G_CONST_RETURN gchar *
3467 glib_gettext (const gchar *str)
3468 {
3469   static gboolean _glib_gettext_initialized = FALSE;
3470
3471   if (!_glib_gettext_initialized)
3472     {
3473 #ifdef G_OS_WIN32
3474       gchar *tmp = _glib_get_locale_dir ();
3475       bindtextdomain (GETTEXT_PACKAGE, tmp);
3476       g_free (tmp);
3477 #else
3478       bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3479 #endif
3480 #    ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3481       bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3482 #    endif
3483       _glib_gettext_initialized = TRUE;
3484     }
3485   
3486   return g_dgettext (GETTEXT_PACKAGE, str);
3487 }
3488
3489 #if defined (G_OS_WIN32) && !defined (_WIN64)
3490
3491 /* Binary compatibility versions. Not for newly compiled code. */
3492
3493 #undef g_find_program_in_path
3494
3495 gchar*
3496 g_find_program_in_path (const gchar *program)
3497 {
3498   gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3499   gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3500   gchar *retval;
3501
3502   g_free (utf8_program);
3503   if (utf8_retval == NULL)
3504     return NULL;
3505   retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3506   g_free (utf8_retval);
3507
3508   return retval;
3509 }
3510
3511 #undef g_get_current_dir
3512
3513 gchar*
3514 g_get_current_dir (void)
3515 {
3516   gchar *utf8_dir = g_get_current_dir_utf8 ();
3517   gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3518   g_free (utf8_dir);
3519   return dir;
3520 }
3521
3522 #undef g_getenv
3523
3524 G_CONST_RETURN gchar*
3525 g_getenv (const gchar *variable)
3526 {
3527   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3528   const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3529   gchar *value;
3530   GQuark quark;
3531
3532   g_free (utf8_variable);
3533   if (!utf8_value)
3534     return NULL;
3535   value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3536   quark = g_quark_from_string (value);
3537   g_free (value);
3538
3539   return g_quark_to_string (quark);
3540 }
3541
3542 #undef g_setenv
3543
3544 gboolean
3545 g_setenv (const gchar *variable, 
3546           const gchar *value, 
3547           gboolean     overwrite)
3548 {
3549   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3550   gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3551   gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3552
3553   g_free (utf8_variable);
3554   g_free (utf8_value);
3555
3556   return retval;
3557 }
3558
3559 #undef g_unsetenv
3560
3561 void
3562 g_unsetenv (const gchar *variable)
3563 {
3564   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3565
3566   g_unsetenv_utf8 (utf8_variable);
3567
3568   g_free (utf8_variable);
3569 }
3570
3571 #undef g_get_user_name
3572
3573 G_CONST_RETURN gchar*
3574 g_get_user_name (void)
3575 {
3576   g_get_any_init_locked ();
3577   return g_user_name_cp;
3578 }
3579
3580 #undef g_get_real_name
3581
3582 G_CONST_RETURN gchar*
3583 g_get_real_name (void)
3584 {
3585   g_get_any_init_locked ();
3586   return g_real_name_cp;
3587 }
3588
3589 #undef g_get_home_dir
3590
3591 G_CONST_RETURN gchar*
3592 g_get_home_dir (void)
3593 {
3594   g_get_any_init_locked ();
3595   return g_home_dir_cp;
3596 }
3597
3598 #undef g_get_tmp_dir
3599
3600 G_CONST_RETURN gchar*
3601 g_get_tmp_dir (void)
3602 {
3603   g_get_any_init_locked ();
3604   return g_tmp_dir_cp;
3605 }
3606
3607 #endif