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