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