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