Guarantee that g_get_tmp_dir () doesn't return an empty string
[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   static const GUID FOLDERID_Downloads =
2281     { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2282   static const GUID FOLDERID_Public =
2283     { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2284   wchar_t *wcp;
2285
2286   p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (LoadLibrary ("shell32.dll"),
2287                                                                     "SHGetKnownFolderPath");
2288
2289   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2290   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2291
2292   if (p_SHGetKnownFolderPath == NULL)
2293     {
2294       g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2295     }
2296   else
2297     {
2298       wcp = NULL;
2299       (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2300       g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2301       if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2302         g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2303       CoTaskMemFree (wcp);
2304     }
2305
2306   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2307   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2308
2309   if (p_SHGetKnownFolderPath == NULL)
2310     {
2311       /* XXX */
2312       g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2313     }
2314   else
2315     {
2316       wcp = NULL;
2317       (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2318       g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2319       if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2320         g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2321       CoTaskMemFree (wcp);
2322     }
2323   
2324   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2325   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2326 }
2327 #endif /* G_OS_WIN32 */
2328
2329 static void g_init_user_config_dir (void);
2330
2331 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2332
2333 /* adapted from xdg-user-dir-lookup.c
2334  *
2335  * Copyright (C) 2007 Red Hat Inc.
2336  *
2337  * Permission is hereby granted, free of charge, to any person
2338  * obtaining a copy of this software and associated documentation files
2339  * (the "Software"), to deal in the Software without restriction,
2340  * including without limitation the rights to use, copy, modify, merge,
2341  * publish, distribute, sublicense, and/or sell copies of the Software,
2342  * and to permit persons to whom the Software is furnished to do so,
2343  * subject to the following conditions: 
2344  *
2345  * The above copyright notice and this permission notice shall be
2346  * included in all copies or substantial portions of the Software. 
2347  *
2348  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2349  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2350  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2351  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2352  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2353  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2354  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2355  * SOFTWARE.
2356  */
2357 static void
2358 load_user_special_dirs (void)
2359 {
2360   gchar *config_file;
2361   gchar *data;
2362   gchar **lines;
2363   gint n_lines, i;
2364   
2365   g_init_user_config_dir ();
2366   config_file = g_build_filename (g_user_config_dir,
2367                                   "user-dirs.dirs",
2368                                   NULL);
2369   
2370   if (!g_file_get_contents (config_file, &data, NULL, NULL))
2371     {
2372       g_free (config_file);
2373       return;
2374     }
2375
2376   lines = g_strsplit (data, "\n", -1);
2377   n_lines = g_strv_length (lines);
2378   g_free (data);
2379   
2380   for (i = 0; i < n_lines; i++)
2381     {
2382       gchar *buffer = lines[i];
2383       gchar *d, *p;
2384       gint len;
2385       gboolean is_relative = FALSE;
2386       GUserDirectory directory;
2387
2388       /* Remove newline at end */
2389       len = strlen (buffer);
2390       if (len > 0 && buffer[len - 1] == '\n')
2391         buffer[len - 1] = 0;
2392       
2393       p = buffer;
2394       while (*p == ' ' || *p == '\t')
2395         p++;
2396       
2397       if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2398         {
2399           directory = G_USER_DIRECTORY_DESKTOP;
2400           p += strlen ("XDG_DESKTOP_DIR");
2401         }
2402       else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2403         {
2404           directory = G_USER_DIRECTORY_DOCUMENTS;
2405           p += strlen ("XDG_DOCUMENTS_DIR");
2406         }
2407       else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2408         {
2409           directory = G_USER_DIRECTORY_DOWNLOAD;
2410           p += strlen ("XDG_DOWNLOAD_DIR");
2411         }
2412       else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2413         {
2414           directory = G_USER_DIRECTORY_MUSIC;
2415           p += strlen ("XDG_MUSIC_DIR");
2416         }
2417       else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2418         {
2419           directory = G_USER_DIRECTORY_PICTURES;
2420           p += strlen ("XDG_PICTURES_DIR");
2421         }
2422       else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2423         {
2424           directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2425           p += strlen ("XDG_PUBLICSHARE_DIR");
2426         }
2427       else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2428         {
2429           directory = G_USER_DIRECTORY_TEMPLATES;
2430           p += strlen ("XDG_TEMPLATES_DIR");
2431         }
2432       else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2433         {
2434           directory = G_USER_DIRECTORY_VIDEOS;
2435           p += strlen ("XDG_VIDEOS_DIR");
2436         }
2437       else
2438         continue;
2439
2440       while (*p == ' ' || *p == '\t')
2441         p++;
2442
2443       if (*p != '=')
2444         continue;
2445       p++;
2446
2447       while (*p == ' ' || *p == '\t')
2448         p++;
2449
2450       if (*p != '"')
2451         continue;
2452       p++;
2453
2454       if (strncmp (p, "$HOME", 5) == 0)
2455         {
2456           p += 5;
2457           is_relative = TRUE;
2458         }
2459       else if (*p != '/')
2460         continue;
2461
2462       d = strrchr (p, '"');
2463       if (!d)
2464         continue;
2465       *d = 0;
2466
2467       d = p;
2468       
2469       /* remove trailing slashes */
2470       len = strlen (d);
2471       if (d[len - 1] == '/')
2472         d[len - 1] = 0;
2473       
2474       if (is_relative)
2475         {
2476           g_get_any_init ();
2477           g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2478         }
2479       else
2480         g_user_special_dirs[directory] = g_strdup (d);
2481     }
2482
2483   g_strfreev (lines);
2484   g_free (config_file);
2485 }
2486
2487 #endif /* G_OS_UNIX && !HAVE_CARBON */
2488
2489
2490 /**
2491  * g_reload_user_special_dirs_cache:
2492  *
2493  * Resets the cache used for g_get_user_special_dir(), so
2494  * that the latest on-disk version is used. Call this only
2495  * if you just changed the data on disk yourself.
2496  *
2497  * Due to threadsafety issues this may cause leaking of strings
2498  * that were previously returned from g_get_user_special_dir()
2499  * that can't be freed. We ensure to only leak the data for
2500  * the directories that actually changed value though.
2501  *
2502  * Since: 2.22
2503  */
2504 void
2505 g_reload_user_special_dirs_cache (void)
2506 {
2507   int i;
2508
2509   G_LOCK (g_utils_global);
2510
2511   if (g_user_special_dirs != NULL)
2512     {
2513       /* save a copy of the pointer, to check if some memory can be preserved */
2514       char **old_g_user_special_dirs = g_user_special_dirs;
2515       char *old_val;
2516
2517       /* recreate and reload our cache */
2518       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2519       load_user_special_dirs ();
2520
2521       /* only leak changed directories */
2522       for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2523         {
2524           old_val = old_g_user_special_dirs[i];
2525           if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2526             {
2527               /* don't leak */
2528               g_free (g_user_special_dirs[i]);
2529               g_user_special_dirs[i] = old_val;
2530             }
2531           else
2532             g_free (old_val);
2533         }
2534
2535       /* free the old array */
2536       g_free (old_g_user_special_dirs);
2537     }
2538
2539   G_UNLOCK (g_utils_global);
2540 }
2541
2542 /**
2543  * g_get_user_special_dir:
2544  * @directory: the logical id of special directory
2545  *
2546  * Returns the full path of a special directory using its logical id.
2547  *
2548  * On Unix this is done using the XDG special user directories.
2549  * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2550  * falls back to <filename>$HOME/Desktop</filename> when XDG special
2551  * user directories have not been set up. 
2552  *
2553  * Depending on the platform, the user might be able to change the path
2554  * of the special directory without requiring the session to restart; GLib
2555  * will not reflect any change once the special directories are loaded.
2556  *
2557  * Return value: the path to the specified special directory, or %NULL
2558  *   if the logical id was not found. The returned string is owned by
2559  *   GLib and should not be modified or freed.
2560  *
2561  * Since: 2.14
2562  */
2563 G_CONST_RETURN gchar *
2564 g_get_user_special_dir (GUserDirectory directory)
2565 {
2566   g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2567                         directory < G_USER_N_DIRECTORIES, NULL);
2568
2569   G_LOCK (g_utils_global);
2570
2571   if (G_UNLIKELY (g_user_special_dirs == NULL))
2572     {
2573       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2574
2575       load_user_special_dirs ();
2576
2577       /* Special-case desktop for historical compatibility */
2578       if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2579         {
2580           g_get_any_init ();
2581
2582           g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2583             g_build_filename (g_home_dir, "Desktop", NULL);
2584         }
2585     }
2586
2587   G_UNLOCK (g_utils_global);
2588
2589   return g_user_special_dirs[directory];
2590 }
2591
2592 #ifdef G_OS_WIN32
2593
2594 #undef g_get_system_data_dirs
2595
2596 static HMODULE
2597 get_module_for_address (gconstpointer address)
2598 {
2599   /* Holds the g_utils_global lock */
2600
2601   static gboolean beenhere = FALSE;
2602   typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2603   static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2604   HMODULE hmodule = NULL;
2605
2606   if (!address)
2607     return NULL;
2608
2609   if (!beenhere)
2610     {
2611       p_GetModuleHandleExA =
2612         (t_GetModuleHandleExA) GetProcAddress (LoadLibrary ("kernel32.dll"),
2613                                                "GetModuleHandleExA");
2614       beenhere = TRUE;
2615     }
2616
2617   if (p_GetModuleHandleExA == NULL ||
2618       !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2619                                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2620                                 address, &hmodule))
2621     {
2622       MEMORY_BASIC_INFORMATION mbi;
2623       VirtualQuery (address, &mbi, sizeof (mbi));
2624       hmodule = (HMODULE) mbi.AllocationBase;
2625     }
2626
2627   return hmodule;
2628 }
2629
2630 static gchar *
2631 get_module_share_dir (gconstpointer address)
2632 {
2633   HMODULE hmodule;
2634   gchar *filename;
2635   gchar *retval;
2636
2637   hmodule = get_module_for_address (address);
2638   if (hmodule == NULL)
2639     return NULL;
2640
2641   filename = g_win32_get_package_installation_directory_of_module (hmodule);
2642   retval = g_build_filename (filename, "share", NULL);
2643   g_free (filename);
2644
2645   return retval;
2646 }
2647
2648 G_CONST_RETURN gchar * G_CONST_RETURN *
2649 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2650 {
2651   GArray *data_dirs;
2652   HMODULE hmodule;
2653   static GHashTable *per_module_data_dirs = NULL;
2654   gchar **retval;
2655   gchar *p;
2656   gchar *exe_root;
2657       
2658   if (address_of_function)
2659     {
2660       G_LOCK (g_utils_global);
2661       hmodule = get_module_for_address (address_of_function);
2662       if (hmodule != NULL)
2663         {
2664           if (per_module_data_dirs == NULL)
2665             per_module_data_dirs = g_hash_table_new (NULL, NULL);
2666           else
2667             {
2668               retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2669               
2670               if (retval != NULL)
2671                 {
2672                   G_UNLOCK (g_utils_global);
2673                   return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2674                 }
2675             }
2676         }
2677     }
2678
2679   data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2680
2681   /* Documents and Settings\All Users\Application Data */
2682   p = get_special_folder (CSIDL_COMMON_APPDATA);
2683   if (p)
2684     g_array_append_val (data_dirs, p);
2685   
2686   /* Documents and Settings\All Users\Documents */
2687   p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2688   if (p)
2689     g_array_append_val (data_dirs, p);
2690         
2691   /* Using the above subfolders of Documents and Settings perhaps
2692    * makes sense from a Windows perspective.
2693    *
2694    * But looking at the actual use cases of this function in GTK+
2695    * and GNOME software, what we really want is the "share"
2696    * subdirectory of the installation directory for the package
2697    * our caller is a part of.
2698    *
2699    * The address_of_function parameter, if non-NULL, points to a
2700    * function in the calling module. Use that to determine that
2701    * module's installation folder, and use its "share" subfolder.
2702    *
2703    * Additionally, also use the "share" subfolder of the installation
2704    * locations of GLib and the .exe file being run.
2705    *
2706    * To guard against none of the above being what is really wanted,
2707    * callers of this function should have Win32-specific code to look
2708    * up their installation folder themselves, and handle a subfolder
2709    * "share" of it in the same way as the folders returned from this
2710    * function.
2711    */
2712
2713   p = get_module_share_dir (address_of_function);
2714   if (p)
2715     g_array_append_val (data_dirs, p);
2716     
2717   if (glib_dll != NULL)
2718     {
2719       gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2720       p = g_build_filename (glib_root, "share", NULL);
2721       if (p)
2722         g_array_append_val (data_dirs, p);
2723       g_free (glib_root);
2724     }
2725   
2726   exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2727   p = g_build_filename (exe_root, "share", NULL);
2728   if (p)
2729     g_array_append_val (data_dirs, p);
2730   g_free (exe_root);
2731
2732   retval = (gchar **) g_array_free (data_dirs, FALSE);
2733
2734   if (address_of_function)
2735     {
2736       if (hmodule != NULL)
2737         g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2738       G_UNLOCK (g_utils_global);
2739     }
2740
2741   return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2742 }
2743
2744 #endif
2745
2746 /**
2747  * g_get_system_data_dirs:
2748  * 
2749  * Returns an ordered list of base directories in which to access 
2750  * system-wide application data.
2751  *
2752  * On UNIX platforms this is determined using the mechanisms described in
2753  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2754  * XDG Base Directory Specification</ulink>
2755  * In this case the list of directories retrieved will be XDG_DATA_DIRS.
2756  *
2757  * On Windows the first elements in the list are the Application Data
2758  * and Documents folders for All Users. (These can be determined only
2759  * on Windows 2000 or later and are not present in the list on other
2760  * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2761  * CSIDL_COMMON_DOCUMENTS.
2762  *
2763  * Then follows the "share" subfolder in the installation folder for
2764  * the package containing the DLL that calls this function, if it can
2765  * be determined.
2766  * 
2767  * Finally the list contains the "share" subfolder in the installation
2768  * folder for GLib, and in the installation folder for the package the
2769  * application's .exe file belongs to.
2770  *
2771  * The installation folders above are determined by looking up the
2772  * folder where the module (DLL or EXE) in question is located. If the
2773  * folder's name is "bin", its parent is used, otherwise the folder
2774  * itself.
2775  *
2776  * Note that on Windows the returned list can vary depending on where
2777  * this function is called.
2778  *
2779  * Return value: a %NULL-terminated array of strings owned by GLib that must 
2780  *               not be modified or freed.
2781  * Since: 2.6
2782  **/
2783 G_CONST_RETURN gchar * G_CONST_RETURN * 
2784 g_get_system_data_dirs (void)
2785 {
2786   gchar **data_dir_vector;
2787
2788   G_LOCK (g_utils_global);
2789
2790   if (!g_system_data_dirs)
2791     {
2792 #ifdef G_OS_WIN32
2793       data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2794 #else
2795       gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2796
2797       if (!data_dirs || !data_dirs[0])
2798           data_dirs = "/usr/local/share/:/usr/share/";
2799
2800       data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2801 #endif
2802
2803       g_system_data_dirs = data_dir_vector;
2804     }
2805   else
2806     data_dir_vector = g_system_data_dirs;
2807
2808   G_UNLOCK (g_utils_global);
2809
2810   return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2811 }
2812
2813 /**
2814  * g_get_system_config_dirs:
2815  * 
2816  * Returns an ordered list of base directories in which to access 
2817  * system-wide configuration information.
2818  *
2819  * On UNIX platforms this is determined using the mechanisms described in
2820  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2821  * XDG Base Directory Specification</ulink>.
2822  * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2823  *
2824  * On Windows is the directory that contains application data for all users.
2825  * A typical path is C:\Documents and Settings\All Users\Application Data.
2826  * This folder is used for application data that is not user specific.
2827  * For example, an application can store a spell-check dictionary, a database
2828  * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2829  * This information will not roam and is available to anyone using the computer.
2830  *
2831  * Return value: a %NULL-terminated array of strings owned by GLib that must 
2832  *               not be modified or freed.
2833  * Since: 2.6
2834  **/
2835 G_CONST_RETURN gchar * G_CONST_RETURN *
2836 g_get_system_config_dirs (void)
2837 {
2838   gchar *conf_dirs, **conf_dir_vector;
2839
2840   G_LOCK (g_utils_global);
2841
2842   if (!g_system_config_dirs)
2843     {
2844 #ifdef G_OS_WIN32
2845       conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2846       if (conf_dirs)
2847         {
2848           conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2849           g_free (conf_dirs);
2850         }
2851       else
2852         {
2853           /* Return empty list */
2854           conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2855         }
2856 #else
2857       conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2858
2859       if (!conf_dirs || !conf_dirs[0])
2860           conf_dirs = "/etc/xdg";
2861
2862       conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2863 #endif
2864
2865       g_system_config_dirs = conf_dir_vector;
2866     }
2867   else
2868     conf_dir_vector = g_system_config_dirs;
2869   G_UNLOCK (g_utils_global);
2870
2871   return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2872 }
2873
2874 #ifndef G_OS_WIN32
2875
2876 static GHashTable *alias_table = NULL;
2877
2878 /* read an alias file for the locales */
2879 static void
2880 read_aliases (gchar *file)
2881 {
2882   FILE *fp;
2883   char buf[256];
2884   
2885   if (!alias_table)
2886     alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2887   fp = fopen (file,"r");
2888   if (!fp)
2889     return;
2890   while (fgets (buf, 256, fp))
2891     {
2892       char *p, *q;
2893
2894       g_strstrip (buf);
2895
2896       /* Line is a comment */
2897       if ((buf[0] == '#') || (buf[0] == '\0'))
2898         continue;
2899
2900       /* Reads first column */
2901       for (p = buf, q = NULL; *p; p++) {
2902         if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2903           *p = '\0';
2904           q = p+1;
2905           while ((*q == '\t') || (*q == ' ')) {
2906             q++;
2907           }
2908           break;
2909         }
2910       }
2911       /* The line only had one column */
2912       if (!q || *q == '\0')
2913         continue;
2914       
2915       /* Read second column */
2916       for (p = q; *p; p++) {
2917         if ((*p == '\t') || (*p == ' ')) {
2918           *p = '\0';
2919           break;
2920         }
2921       }
2922
2923       /* Add to alias table if necessary */
2924       if (!g_hash_table_lookup (alias_table, buf)) {
2925         g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2926       }
2927     }
2928   fclose (fp);
2929 }
2930
2931 #endif
2932
2933 static char *
2934 unalias_lang (char *lang)
2935 {
2936 #ifndef G_OS_WIN32
2937   char *p;
2938   int i;
2939
2940   if (!alias_table)
2941     read_aliases ("/usr/share/locale/locale.alias");
2942
2943   i = 0;
2944   while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2945     {
2946       lang = p;
2947       if (i++ == 30)
2948         {
2949           static gboolean said_before = FALSE;
2950           if (!said_before)
2951             g_warning ("Too many alias levels for a locale, "
2952                        "may indicate a loop");
2953           said_before = TRUE;
2954           return lang;
2955         }
2956     }
2957 #endif
2958   return lang;
2959 }
2960
2961 /* Mask for components of locale spec. The ordering here is from
2962  * least significant to most significant
2963  */
2964 enum
2965 {
2966   COMPONENT_CODESET =   1 << 0,
2967   COMPONENT_TERRITORY = 1 << 1,
2968   COMPONENT_MODIFIER =  1 << 2
2969 };
2970
2971 /* Break an X/Open style locale specification into components
2972  */
2973 static guint
2974 explode_locale (const gchar *locale,
2975                 gchar      **language, 
2976                 gchar      **territory, 
2977                 gchar      **codeset, 
2978                 gchar      **modifier)
2979 {
2980   const gchar *uscore_pos;
2981   const gchar *at_pos;
2982   const gchar *dot_pos;
2983
2984   guint mask = 0;
2985
2986   uscore_pos = strchr (locale, '_');
2987   dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2988   at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2989
2990   if (at_pos)
2991     {
2992       mask |= COMPONENT_MODIFIER;
2993       *modifier = g_strdup (at_pos);
2994     }
2995   else
2996     at_pos = locale + strlen (locale);
2997
2998   if (dot_pos)
2999     {
3000       mask |= COMPONENT_CODESET;
3001       *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3002     }
3003   else
3004     dot_pos = at_pos;
3005
3006   if (uscore_pos)
3007     {
3008       mask |= COMPONENT_TERRITORY;
3009       *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3010     }
3011   else
3012     uscore_pos = dot_pos;
3013
3014   *language = g_strndup (locale, uscore_pos - locale);
3015
3016   return mask;
3017 }
3018
3019 /*
3020  * Compute all interesting variants for a given locale name -
3021  * by stripping off different components of the value.
3022  *
3023  * For simplicity, we assume that the locale is in
3024  * X/Open format: language[_territory][.codeset][@modifier]
3025  *
3026  * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3027  *       as well. We could just copy the code from glibc wholesale
3028  *       but it is big, ugly, and complicated, so I'm reluctant
3029  *       to do so when this should handle 99% of the time...
3030  */
3031 GSList *
3032 _g_compute_locale_variants (const gchar *locale)
3033 {
3034   GSList *retval = NULL;
3035
3036   gchar *language = NULL;
3037   gchar *territory = NULL;
3038   gchar *codeset = NULL;
3039   gchar *modifier = NULL;
3040
3041   guint mask;
3042   guint i;
3043
3044   g_return_val_if_fail (locale != NULL, NULL);
3045
3046   mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3047
3048   /* Iterate through all possible combinations, from least attractive
3049    * to most attractive.
3050    */
3051   for (i = 0; i <= mask; i++)
3052     if ((i & ~mask) == 0)
3053       {
3054         gchar *val = g_strconcat (language,
3055                                   (i & COMPONENT_TERRITORY) ? territory : "",
3056                                   (i & COMPONENT_CODESET) ? codeset : "",
3057                                   (i & COMPONENT_MODIFIER) ? modifier : "",
3058                                   NULL);
3059         retval = g_slist_prepend (retval, val);
3060       }
3061
3062   g_free (language);
3063   if (mask & COMPONENT_CODESET)
3064     g_free (codeset);
3065   if (mask & COMPONENT_TERRITORY)
3066     g_free (territory);
3067   if (mask & COMPONENT_MODIFIER)
3068     g_free (modifier);
3069
3070   return retval;
3071 }
3072
3073 /* The following is (partly) taken from the gettext package.
3074    Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc.  */
3075
3076 static const gchar *
3077 guess_category_value (const gchar *category_name)
3078 {
3079   const gchar *retval;
3080
3081   /* The highest priority value is the `LANGUAGE' environment
3082      variable.  This is a GNU extension.  */
3083   retval = g_getenv ("LANGUAGE");
3084   if ((retval != NULL) && (retval[0] != '\0'))
3085     return retval;
3086
3087   /* `LANGUAGE' is not set.  So we have to proceed with the POSIX
3088      methods of looking to `LC_ALL', `LC_xxx', and `LANG'.  On some
3089      systems this can be done by the `setlocale' function itself.  */
3090
3091   /* Setting of LC_ALL overwrites all other.  */
3092   retval = g_getenv ("LC_ALL");  
3093   if ((retval != NULL) && (retval[0] != '\0'))
3094     return retval;
3095
3096   /* Next comes the name of the desired category.  */
3097   retval = g_getenv (category_name);
3098   if ((retval != NULL) && (retval[0] != '\0'))
3099     return retval;
3100
3101   /* Last possibility is the LANG environment variable.  */
3102   retval = g_getenv ("LANG");
3103   if ((retval != NULL) && (retval[0] != '\0'))
3104     return retval;
3105
3106 #ifdef G_PLATFORM_WIN32
3107   /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3108    * LANG, which we already did above. Oh well. The main point of
3109    * calling g_win32_getlocale() is to get the thread's locale as used
3110    * by Windows and the Microsoft C runtime (in the "English_United
3111    * States" format) translated into the Unixish format.
3112    */
3113   {
3114     char *locale = g_win32_getlocale ();
3115     retval = g_intern_string (locale);
3116     g_free (locale);
3117     return retval;
3118   }
3119 #endif  
3120
3121   return NULL;
3122 }
3123
3124 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3125
3126 struct _GLanguageNamesCache {
3127   gchar *languages;
3128   gchar **language_names;
3129 };
3130
3131 static void
3132 language_names_cache_free (gpointer data)
3133 {
3134   GLanguageNamesCache *cache = data;
3135   g_free (cache->languages);
3136   g_strfreev (cache->language_names);
3137   g_free (cache);
3138 }
3139
3140 /**
3141  * g_get_language_names:
3142  * 
3143  * Computes a list of applicable locale names, which can be used to 
3144  * e.g. construct locale-dependent filenames or search paths. The returned 
3145  * list is sorted from most desirable to least desirable and always contains 
3146  * the default locale "C".
3147  *
3148  * For example, if LANGUAGE=de:en_US, then the returned list is
3149  * "de", "en_US", "en", "C".
3150  *
3151  * This function consults the environment variables <envar>LANGUAGE</envar>, 
3152  * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar> 
3153  * to find the list of locales specified by the user.
3154  * 
3155  * Return value: a %NULL-terminated array of strings owned by GLib 
3156  *    that must not be modified or freed.
3157  *
3158  * Since: 2.6
3159  **/
3160 G_CONST_RETURN gchar * G_CONST_RETURN * 
3161 g_get_language_names (void)
3162 {
3163   static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3164   GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3165   const gchar *value;
3166
3167   if (!cache)
3168     {
3169       cache = g_new0 (GLanguageNamesCache, 1);
3170       g_static_private_set (&cache_private, cache, language_names_cache_free);
3171     }
3172
3173   value = guess_category_value ("LC_MESSAGES");
3174   if (!value)
3175     value = "C";
3176
3177   if (!(cache->languages && strcmp (cache->languages, value) == 0))
3178     {
3179       gchar **languages;
3180       gchar **alist, **a;
3181       GSList *list, *l;
3182       gint i;
3183
3184       g_free (cache->languages);
3185       g_strfreev (cache->language_names);
3186       cache->languages = g_strdup (value);
3187
3188       alist = g_strsplit (value, ":", 0);
3189       list = NULL;
3190       for (a = alist; *a; a++)
3191         {
3192           gchar *b = unalias_lang (*a);
3193           list = g_slist_concat (list, _g_compute_locale_variants (b));
3194         }
3195       g_strfreev (alist);
3196       list = g_slist_append (list, g_strdup ("C"));
3197
3198       cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
3199       for (l = list, i = 0; l; l = l->next, i++)
3200         languages[i] = l->data;
3201       languages[i] = NULL;
3202
3203       g_slist_free (list);
3204     }
3205
3206   return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3207 }
3208
3209 /**
3210  * g_direct_hash:
3211  * @v: a #gpointer key
3212  *
3213  * Converts a gpointer to a hash value.
3214  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
3215  * when using pointers as keys in a #GHashTable.
3216  *
3217  * Returns: a hash value corresponding to the key.
3218  */
3219 guint
3220 g_direct_hash (gconstpointer v)
3221 {
3222   return GPOINTER_TO_UINT (v);
3223 }
3224
3225 /**
3226  * g_direct_equal:
3227  * @v1: a key.
3228  * @v2: a key to compare with @v1.
3229  *
3230  * Compares two #gpointer arguments and returns %TRUE if they are equal.
3231  * It can be passed to g_hash_table_new() as the @key_equal_func
3232  * parameter, when using pointers as keys in a #GHashTable.
3233  * 
3234  * Returns: %TRUE if the two keys match.
3235  */
3236 gboolean
3237 g_direct_equal (gconstpointer v1,
3238                 gconstpointer v2)
3239 {
3240   return v1 == v2;
3241 }
3242
3243 /**
3244  * g_int_equal:
3245  * @v1: a pointer to a #gint key.
3246  * @v2: a pointer to a #gint key to compare with @v1.
3247  *
3248  * Compares the two #gint values being pointed to and returns 
3249  * %TRUE if they are equal.
3250  * It can be passed to g_hash_table_new() as the @key_equal_func
3251  * parameter, when using pointers to integers as keys in a #GHashTable.
3252  * 
3253  * Returns: %TRUE if the two keys match.
3254  */
3255 gboolean
3256 g_int_equal (gconstpointer v1,
3257              gconstpointer v2)
3258 {
3259   return *((const gint*) v1) == *((const gint*) v2);
3260 }
3261
3262 /**
3263  * g_int_hash:
3264  * @v: a pointer to a #gint key
3265  *
3266  * Converts a pointer to a #gint to a hash value.
3267  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
3268  * when using pointers to integers values as keys in a #GHashTable.
3269  *
3270  * Returns: a hash value corresponding to the key.
3271  */
3272 guint
3273 g_int_hash (gconstpointer v)
3274 {
3275   return *(const gint*) v;
3276 }
3277
3278 /**
3279  * g_int64_equal:
3280  * @v1: a pointer to a #gint64 key.
3281  * @v2: a pointer to a #gint64 key to compare with @v1.
3282  *
3283  * Compares the two #gint64 values being pointed to and returns 
3284  * %TRUE if they are equal.
3285  * It can be passed to g_hash_table_new() as the @key_equal_func
3286  * parameter, when using pointers to 64-bit integers as keys in a #GHashTable.
3287  * 
3288  * Returns: %TRUE if the two keys match.
3289  *
3290  * Since: 2.22
3291  */
3292 gboolean
3293 g_int64_equal (gconstpointer v1,
3294                gconstpointer v2)
3295 {
3296   return *((const gint64*) v1) == *((const gint64*) v2);
3297 }
3298
3299 /**
3300  * g_int64_hash:
3301  * @v: a pointer to a #gint64 key
3302  *
3303  * Converts a pointer to a #gint64 to a hash value.
3304  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
3305  * when using pointers to 64-bit integers values as keys in a #GHashTable.
3306  *
3307  * Returns: a hash value corresponding to the key.
3308  *
3309  * Since: 2.22
3310  */
3311 guint
3312 g_int64_hash (gconstpointer v)
3313 {
3314   return (guint) *(const gint64*) v;
3315 }
3316
3317 /**
3318  * g_double_equal:
3319  * @v1: a pointer to a #gdouble key.
3320  * @v2: a pointer to a #gdouble key to compare with @v1.
3321  *
3322  * Compares the two #gdouble values being pointed to and returns 
3323  * %TRUE if they are equal.
3324  * It can be passed to g_hash_table_new() as the @key_equal_func
3325  * parameter, when using pointers to doubles as keys in a #GHashTable.
3326  * 
3327  * Returns: %TRUE if the two keys match.
3328  *
3329  * Since: 2.22
3330  */
3331 gboolean
3332 g_double_equal (gconstpointer v1,
3333                 gconstpointer v2)
3334 {
3335   return *((const gdouble*) v1) == *((const gdouble*) v2);
3336 }
3337
3338 /**
3339  * g_double_hash:
3340  * @v: a pointer to a #gdouble key
3341  *
3342  * Converts a pointer to a #gdouble to a hash value.
3343  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
3344  * when using pointers to doubles as keys in a #GHashTable.
3345  *
3346  * Returns: a hash value corresponding to the key.
3347  *
3348  * Since: 2.22
3349  */
3350 guint
3351 g_double_hash (gconstpointer v)
3352 {
3353   return (guint) *(const gdouble*) v;
3354 }
3355
3356 /**
3357  * g_nullify_pointer:
3358  * @nullify_location: the memory address of the pointer.
3359  * 
3360  * Set the pointer at the specified location to %NULL.
3361  **/
3362 void
3363 g_nullify_pointer (gpointer *nullify_location)
3364 {
3365   g_return_if_fail (nullify_location != NULL);
3366
3367   *nullify_location = NULL;
3368 }
3369
3370 /**
3371  * g_get_codeset:
3372  * 
3373  * Get the codeset for the current locale.
3374  * 
3375  * Return value: a newly allocated string containing the name
3376  * of the codeset. This string must be freed with g_free().
3377  **/
3378 gchar *
3379 g_get_codeset (void)
3380 {
3381   const gchar *charset;
3382
3383   g_get_charset (&charset);
3384
3385   return g_strdup (charset);
3386 }
3387
3388 /* This is called from g_thread_init(). It's used to
3389  * initialize some static data in a threadsafe way.
3390  */
3391 void
3392 _g_utils_thread_init (void)
3393 {
3394   g_get_language_names ();
3395 }
3396
3397 #ifdef G_OS_WIN32
3398
3399 /**
3400  * _glib_get_locale_dir:
3401  *
3402  * Return the path to the share\locale or lib\locale subfolder of the
3403  * GLib installation folder. The path is in the system codepage. We
3404  * have to use system codepage as bindtextdomain() doesn't have a
3405  * UTF-8 interface.
3406  */
3407 static gchar *
3408 _glib_get_locale_dir (void)
3409 {
3410   gchar *install_dir = NULL, *locale_dir;
3411   gchar *retval = NULL;
3412
3413   if (glib_dll != NULL)
3414     install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3415
3416   if (install_dir)
3417     {
3418       /*
3419        * Append "/share/locale" or "/lib/locale" depending on whether
3420        * autoconfigury detected GNU gettext or not.
3421        */
3422       const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3423       while (*--p != '/')
3424         ;
3425       while (*--p != '/')
3426         ;
3427
3428       locale_dir = g_build_filename (install_dir, p, NULL);
3429
3430       retval = g_win32_locale_filename_from_utf8 (locale_dir);
3431
3432       g_free (install_dir);
3433       g_free (locale_dir);
3434     }
3435
3436   if (retval)
3437     return retval;
3438   else
3439     return g_strdup ("");
3440 }
3441
3442 #undef GLIB_LOCALE_DIR
3443
3444 #endif /* G_OS_WIN32 */
3445
3446 /**
3447  * glib_gettext:
3448  * @str: The string to be translated
3449  *
3450  * Returns the translated string from the glib translations.
3451  * This is an internal function and should only be used by
3452  * the internals of glib (such as libgio).
3453  *
3454  * Returns: the transation of @str to the current locale
3455  */
3456 G_CONST_RETURN gchar *
3457 glib_gettext (const gchar *str)
3458 {
3459   static gboolean _glib_gettext_initialized = FALSE;
3460
3461   if (!_glib_gettext_initialized)
3462     {
3463 #ifdef G_OS_WIN32
3464       gchar *tmp = _glib_get_locale_dir ();
3465       bindtextdomain (GETTEXT_PACKAGE, tmp);
3466       g_free (tmp);
3467 #else
3468       bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3469 #endif
3470 #    ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3471       bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3472 #    endif
3473       _glib_gettext_initialized = TRUE;
3474     }
3475   
3476   return g_dgettext (GETTEXT_PACKAGE, str);
3477 }
3478
3479 #if defined (G_OS_WIN32) && !defined (_WIN64)
3480
3481 /* Binary compatibility versions. Not for newly compiled code. */
3482
3483 #undef g_find_program_in_path
3484
3485 gchar*
3486 g_find_program_in_path (const gchar *program)
3487 {
3488   gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3489   gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3490   gchar *retval;
3491
3492   g_free (utf8_program);
3493   if (utf8_retval == NULL)
3494     return NULL;
3495   retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3496   g_free (utf8_retval);
3497
3498   return retval;
3499 }
3500
3501 #undef g_get_current_dir
3502
3503 gchar*
3504 g_get_current_dir (void)
3505 {
3506   gchar *utf8_dir = g_get_current_dir_utf8 ();
3507   gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3508   g_free (utf8_dir);
3509   return dir;
3510 }
3511
3512 #undef g_getenv
3513
3514 G_CONST_RETURN gchar*
3515 g_getenv (const gchar *variable)
3516 {
3517   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3518   const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3519   gchar *value;
3520   GQuark quark;
3521
3522   g_free (utf8_variable);
3523   if (!utf8_value)
3524     return NULL;
3525   value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3526   quark = g_quark_from_string (value);
3527   g_free (value);
3528
3529   return g_quark_to_string (quark);
3530 }
3531
3532 #undef g_setenv
3533
3534 gboolean
3535 g_setenv (const gchar *variable, 
3536           const gchar *value, 
3537           gboolean     overwrite)
3538 {
3539   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3540   gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3541   gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3542
3543   g_free (utf8_variable);
3544   g_free (utf8_value);
3545
3546   return retval;
3547 }
3548
3549 #undef g_unsetenv
3550
3551 void
3552 g_unsetenv (const gchar *variable)
3553 {
3554   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3555
3556   g_unsetenv_utf8 (utf8_variable);
3557
3558   g_free (utf8_variable);
3559 }
3560
3561 #undef g_get_user_name
3562
3563 G_CONST_RETURN gchar*
3564 g_get_user_name (void)
3565 {
3566   g_get_any_init_locked ();
3567   return g_user_name_cp;
3568 }
3569
3570 #undef g_get_real_name
3571
3572 G_CONST_RETURN gchar*
3573 g_get_real_name (void)
3574 {
3575   g_get_any_init_locked ();
3576   return g_real_name_cp;
3577 }
3578
3579 #undef g_get_home_dir
3580
3581 G_CONST_RETURN gchar*
3582 g_get_home_dir (void)
3583 {
3584   g_get_any_init_locked ();
3585   return g_home_dir_cp;
3586 }
3587
3588 #undef g_get_tmp_dir
3589
3590 G_CONST_RETURN gchar*
3591 g_get_tmp_dir (void)
3592 {
3593   g_get_any_init_locked ();
3594   return g_tmp_dir_cp;
3595 }
3596
3597 #endif