Add g_key_file_load_from_dirs for looking through a search path for a
[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   gsize len;
395   gsize 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   wchar_t wwindowsdir[MAX_PATH];
1419
1420   if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1421     {
1422       /* Usually X:\Windows, but in terminal server environments
1423        * might be an UNC path, AFAIK.
1424        */
1425       char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1426       char *p;
1427
1428       if (windowsdir == NULL)
1429         return g_strdup ("C:\\");
1430
1431       p = (char *) g_path_skip_root (windowsdir);
1432       if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1433         p--;
1434       *p = '\0';
1435       return windowsdir;
1436     }
1437   else
1438     return g_strdup ("C:\\");
1439 }
1440
1441 #endif
1442
1443 /* HOLDS: g_utils_global_lock */
1444 static void
1445 g_get_any_init_do (void)
1446 {
1447   gchar hostname[100];
1448
1449   g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1450   if (!g_tmp_dir)
1451     g_tmp_dir = g_strdup (g_getenv ("TMP"));
1452   if (!g_tmp_dir)
1453     g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1454
1455 #ifdef G_OS_WIN32
1456   if (!g_tmp_dir)
1457     g_tmp_dir = get_windows_directory_root ();
1458 #else  
1459 #ifdef P_tmpdir
1460   if (!g_tmp_dir)
1461     {
1462       gsize k;    
1463       g_tmp_dir = g_strdup (P_tmpdir);
1464       k = strlen (g_tmp_dir);
1465       if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1466         g_tmp_dir[k - 1] = '\0';
1467     }
1468 #endif
1469   
1470   if (!g_tmp_dir)
1471     {
1472       g_tmp_dir = g_strdup ("/tmp");
1473     }
1474 #endif  /* !G_OS_WIN32 */
1475   
1476 #ifdef G_OS_WIN32
1477   /* We check $HOME first for Win32, though it is a last resort for Unix
1478    * where we prefer the results of getpwuid().
1479    */
1480   g_home_dir = g_strdup (g_getenv ("HOME"));
1481
1482   /* Only believe HOME if it is an absolute path and exists */
1483   if (g_home_dir)
1484     {
1485       if (!(g_path_is_absolute (g_home_dir) &&
1486             g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1487         {
1488           g_free (g_home_dir);
1489           g_home_dir = NULL;
1490         }
1491     }
1492   
1493   /* In case HOME is Unix-style (it happens), convert it to
1494    * Windows style.
1495    */
1496   if (g_home_dir)
1497     {
1498       gchar *p;
1499       while ((p = strchr (g_home_dir, '/')) != NULL)
1500         *p = '\\';
1501     }
1502
1503   if (!g_home_dir)
1504     {
1505       /* USERPROFILE is probably the closest equivalent to $HOME? */
1506       if (g_getenv ("USERPROFILE") != NULL)
1507         g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1508     }
1509
1510   if (!g_home_dir)
1511     g_home_dir = get_special_folder (CSIDL_PROFILE);
1512   
1513   if (!g_home_dir)
1514     g_home_dir = get_windows_directory_root ();
1515 #endif /* G_OS_WIN32 */
1516   
1517 #ifdef HAVE_PWD_H
1518   {
1519     struct passwd *pw = NULL;
1520     gpointer buffer = NULL;
1521     gint error;
1522     gchar *logname;
1523
1524 #  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1525     struct passwd pwd;
1526 #    ifdef _SC_GETPW_R_SIZE_MAX  
1527     /* This reurns the maximum length */
1528     glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1529     
1530     if (bufsize < 0)
1531       bufsize = 64;
1532 #    else /* _SC_GETPW_R_SIZE_MAX */
1533     glong bufsize = 64;
1534 #    endif /* _SC_GETPW_R_SIZE_MAX */
1535
1536     logname = (gchar *) g_getenv ("LOGNAME");
1537         
1538     do
1539       {
1540         g_free (buffer);
1541         /* we allocate 6 extra bytes to work around a bug in 
1542          * Mac OS < 10.3. See #156446
1543          */
1544         buffer = g_malloc (bufsize + 6);
1545         errno = 0;
1546         
1547 #    ifdef HAVE_POSIX_GETPWUID_R
1548         if (logname) {
1549           error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1550           if (!pw || (pw->pw_uid != getuid ())) {
1551             /* LOGNAME is lying, fall back to looking up the uid */
1552             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1553           }
1554         } else {
1555           error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1556         }
1557         error = error < 0 ? errno : error;
1558 #    else /* HAVE_NONPOSIX_GETPWUID_R */
1559    /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1560 #      if defined(_AIX) || defined(__hpux)
1561         error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1562         pw = error == 0 ? &pwd : NULL;
1563 #      else /* !_AIX */
1564         if (logname) {
1565           pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1566           if (!pw || (pw->pw_uid != getuid ())) {
1567             /* LOGNAME is lying, fall back to looking up the uid */
1568             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1569           }
1570         } else {
1571           pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1572         }
1573         error = pw ? 0 : errno;
1574 #      endif /* !_AIX */            
1575 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
1576         
1577         if (!pw)
1578           {
1579             /* we bail out prematurely if the user id can't be found
1580              * (should be pretty rare case actually), or if the buffer
1581              * should be sufficiently big and lookups are still not
1582              * successfull.
1583              */
1584             if (error == 0 || error == ENOENT)
1585               {
1586                 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1587                            (gulong) getuid ());
1588                 break;
1589               }
1590             if (bufsize > 32 * 1024)
1591               {
1592                 g_warning ("getpwuid_r(): failed due to: %s.",
1593                            g_strerror (error));
1594                 break;
1595               }
1596             
1597             bufsize *= 2;
1598           }
1599       }
1600     while (!pw);
1601 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1602     
1603     if (!pw)
1604       {
1605         setpwent ();
1606         pw = getpwuid (getuid ());
1607         endpwent ();
1608       }
1609     if (pw)
1610       {
1611         g_user_name = g_strdup (pw->pw_name);
1612
1613         if (pw->pw_gecos && *pw->pw_gecos != '\0') 
1614           {
1615             gchar **gecos_fields;
1616             gchar **name_parts;
1617
1618             /* split the gecos field and substitute '&' */
1619             gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1620             name_parts = g_strsplit (gecos_fields[0], "&", 0);
1621             pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1622             g_real_name = g_strjoinv (pw->pw_name, name_parts);
1623             g_strfreev (gecos_fields);
1624             g_strfreev (name_parts);
1625           }
1626
1627         if (!g_home_dir)
1628           g_home_dir = g_strdup (pw->pw_dir);
1629       }
1630     g_free (buffer);
1631   }
1632   
1633 #else /* !HAVE_PWD_H */
1634   
1635 #ifdef G_OS_WIN32
1636   {
1637     guint len = UNLEN+1;
1638     wchar_t buffer[UNLEN+1];
1639     
1640     if (GetUserNameW (buffer, (LPDWORD) &len))
1641       {
1642         g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1643         g_real_name = g_strdup (g_user_name);
1644       }
1645   }
1646 #endif /* G_OS_WIN32 */
1647
1648 #endif /* !HAVE_PWD_H */
1649
1650 #ifndef G_OS_WIN32
1651   if (!g_home_dir)
1652     g_home_dir = g_strdup (g_getenv ("HOME"));
1653 #endif
1654
1655 #ifdef __EMX__
1656   /* change '\\' in %HOME% to '/' */
1657   g_strdelimit (g_home_dir, "\\",'/');
1658 #endif
1659   if (!g_user_name)
1660     g_user_name = g_strdup ("somebody");
1661   if (!g_real_name)
1662     g_real_name = g_strdup ("Unknown");
1663
1664   {
1665 #ifndef G_OS_WIN32
1666     gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1667 #else
1668     DWORD size = sizeof (hostname);
1669     gboolean hostname_fail = (!GetComputerName (hostname, &size));
1670 #endif
1671     g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1672   }
1673
1674 #ifdef G_OS_WIN32
1675   g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1676   g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1677   g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1678
1679   if (!g_tmp_dir_cp)
1680     g_tmp_dir_cp = g_strdup ("\\");
1681   if (!g_user_name_cp)
1682     g_user_name_cp = g_strdup ("somebody");
1683   if (!g_real_name_cp)
1684     g_real_name_cp = g_strdup ("Unknown");
1685
1686   /* home_dir might be NULL, unlike tmp_dir, user_name and
1687    * real_name.
1688    */
1689   if (g_home_dir)
1690     g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1691   else
1692     g_home_dir_cp = NULL;
1693 #endif /* G_OS_WIN32 */
1694 }
1695
1696 static inline void
1697 g_get_any_init (void)
1698 {
1699   if (!g_tmp_dir)
1700     g_get_any_init_do ();
1701 }
1702
1703 static inline void
1704 g_get_any_init_locked (void)
1705 {
1706   G_LOCK (g_utils_global);
1707   g_get_any_init ();
1708   G_UNLOCK (g_utils_global);
1709 }
1710
1711
1712 /**
1713  * g_get_user_name:
1714  *
1715  * Gets the user name of the current user. The encoding of the returned
1716  * string is system-defined. On UNIX, it might be the preferred file name
1717  * encoding, or something else, and there is no guarantee that it is even
1718  * consistent on a machine. On Windows, it is always UTF-8.
1719  *
1720  * Returns: the user name of the current user.
1721  */
1722 G_CONST_RETURN gchar*
1723 g_get_user_name (void)
1724 {
1725   g_get_any_init_locked ();
1726   return g_user_name;
1727 }
1728
1729 /**
1730  * g_get_real_name:
1731  *
1732  * Gets the real name of the user. This usually comes from the user's entry 
1733  * in the <filename>passwd</filename> file. The encoding of the returned 
1734  * string is system-defined. (On Windows, it is, however, always UTF-8.) 
1735  * If the real user name cannot be determined, the string "Unknown" is 
1736  * returned.
1737  *
1738  * Returns: the user's real name.
1739  */
1740 G_CONST_RETURN gchar*
1741 g_get_real_name (void)
1742 {
1743   g_get_any_init_locked ();
1744   return g_real_name;
1745 }
1746
1747 /**
1748  * g_get_home_dir:
1749  *
1750  * Gets the current user's home directory as defined in the 
1751  * password database.
1752  *
1753  * Note that in contrast to traditional UNIX tools, this function 
1754  * prefers <filename>passwd</filename> entries over the <envar>HOME</envar> 
1755  * environment variable.
1756  *
1757  * Returns: the current user's home directory.
1758  */
1759 G_CONST_RETURN gchar*
1760 g_get_home_dir (void)
1761 {
1762   g_get_any_init_locked ();
1763   return g_home_dir;
1764 }
1765
1766 /**
1767  * g_get_tmp_dir:
1768  *
1769  * Gets the directory to use for temporary files. This is found from 
1770  * inspecting the environment variables <envar>TMPDIR</envar>, 
1771  * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none 
1772  * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows. 
1773  * The encoding of the returned string is system-defined. On Windows, 
1774  * it is always UTF-8. The return value is never %NULL.
1775  *
1776  * Returns: the directory to use for temporary files.
1777  */
1778 G_CONST_RETURN gchar*
1779 g_get_tmp_dir (void)
1780 {
1781   g_get_any_init_locked ();
1782   return g_tmp_dir;
1783 }
1784
1785 /**
1786  * g_get_host_name:
1787  *
1788  * Return a name for the machine. 
1789  *
1790  * The returned name is not necessarily a fully-qualified domain name,
1791  * or even present in DNS or some other name service at all. It need
1792  * not even be unique on your local network or site, but usually it
1793  * is. Callers should not rely on the return value having any specific
1794  * properties like uniqueness for security purposes. Even if the name
1795  * of the machine is changed while an application is running, the
1796  * return value from this function does not change. The returned
1797  * string is owned by GLib and should not be modified or freed. If no
1798  * name can be determined, a default fixed string "localhost" is
1799  * returned.
1800  *
1801  * Returns: the host name of the machine.
1802  *
1803  * Since: 2.8
1804  */
1805 const gchar *
1806 g_get_host_name (void)
1807 {
1808   g_get_any_init_locked ();
1809   return g_host_name;
1810 }
1811
1812 G_LOCK_DEFINE_STATIC (g_prgname);
1813 static gchar *g_prgname = NULL;
1814
1815 /**
1816  * g_get_prgname:
1817  *
1818  * Gets the name of the program. This name should <emphasis>not</emphasis> 
1819  * be localized, contrast with g_get_application_name().
1820  * (If you are using GDK or GTK+ the program name is set in gdk_init(), 
1821  * which is called by gtk_init(). The program name is found by taking 
1822  * the last component of <literal>argv[0]</literal>.)
1823  *
1824  * Returns: the name of the program. The returned string belongs 
1825  * to GLib and must not be modified or freed.
1826  */
1827 gchar*
1828 g_get_prgname (void)
1829 {
1830   gchar* retval;
1831
1832   G_LOCK (g_prgname);
1833 #ifdef G_OS_WIN32
1834   if (g_prgname == NULL)
1835     {
1836       static gboolean beenhere = FALSE;
1837
1838       if (!beenhere)
1839         {
1840           gchar *utf8_buf = NULL;
1841           wchar_t buf[MAX_PATH+1];
1842
1843           beenhere = TRUE;
1844           if (GetModuleFileNameW (GetModuleHandle (NULL),
1845                                   buf, G_N_ELEMENTS (buf)) > 0)
1846             utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1847
1848           if (utf8_buf)
1849             {
1850               g_prgname = g_path_get_basename (utf8_buf);
1851               g_free (utf8_buf);
1852             }
1853         }
1854     }
1855 #endif
1856   retval = g_prgname;
1857   G_UNLOCK (g_prgname);
1858
1859   return retval;
1860 }
1861
1862 /**
1863  * g_set_prgname:
1864  * @prgname: the name of the program.
1865  *
1866  * Sets the name of the program. This name should <emphasis>not</emphasis> 
1867  * be localized, contrast with g_set_application_name(). Note that for 
1868  * thread-safety reasons this function can only be called once.
1869  */
1870 void
1871 g_set_prgname (const gchar *prgname)
1872 {
1873   G_LOCK (g_prgname);
1874   g_free (g_prgname);
1875   g_prgname = g_strdup (prgname);
1876   G_UNLOCK (g_prgname);
1877 }
1878
1879 G_LOCK_DEFINE_STATIC (g_application_name);
1880 static gchar *g_application_name = NULL;
1881
1882 /**
1883  * g_get_application_name:
1884  * 
1885  * Gets a human-readable name for the application, as set by
1886  * g_set_application_name(). This name should be localized if
1887  * possible, and is intended for display to the user.  Contrast with
1888  * g_get_prgname(), which gets a non-localized name. If
1889  * g_set_application_name() has not been called, returns the result of
1890  * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1891  * been called).
1892  * 
1893  * Return value: human-readable application name. may return %NULL
1894  *
1895  * Since: 2.2
1896  **/
1897 G_CONST_RETURN gchar*
1898 g_get_application_name (void)
1899 {
1900   gchar* retval;
1901
1902   G_LOCK (g_application_name);
1903   retval = g_application_name;
1904   G_UNLOCK (g_application_name);
1905
1906   if (retval == NULL)
1907     return g_get_prgname ();
1908   
1909   return retval;
1910 }
1911
1912 /**
1913  * g_set_application_name:
1914  * @application_name: localized name of the application
1915  *
1916  * Sets a human-readable name for the application. This name should be
1917  * localized if possible, and is intended for display to the user.
1918  * Contrast with g_set_prgname(), which sets a non-localized name.
1919  * g_set_prgname() will be called automatically by gtk_init(),
1920  * but g_set_application_name() will not.
1921  *
1922  * Note that for thread safety reasons, this function can only
1923  * be called once.
1924  *
1925  * The application name will be used in contexts such as error messages,
1926  * or when displaying an application's name in the task list.
1927  * 
1928  **/
1929 void
1930 g_set_application_name (const gchar *application_name)
1931 {
1932   gboolean already_set = FALSE;
1933         
1934   G_LOCK (g_application_name);
1935   if (g_application_name)
1936     already_set = TRUE;
1937   else
1938     g_application_name = g_strdup (application_name);
1939   G_UNLOCK (g_application_name);
1940
1941   if (already_set)
1942     g_warning ("g_set_application() name called multiple times");
1943 }
1944
1945 /**
1946  * g_get_user_data_dir:
1947  * 
1948  * Returns a base directory in which to access application data such
1949  * as icons that is customized for a particular user.  
1950  *
1951  * On UNIX platforms this is determined using the mechanisms described in
1952  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1953  * XDG Base Directory Specification</ulink>
1954  * 
1955  * Return value: a string owned by GLib that must not be modified 
1956  *               or freed.
1957  * Since: 2.6
1958  **/
1959 G_CONST_RETURN gchar*
1960 g_get_user_data_dir (void)
1961 {
1962   gchar *data_dir;  
1963
1964   G_LOCK (g_utils_global);
1965
1966   if (!g_user_data_dir)
1967     {
1968 #ifdef G_OS_WIN32
1969       data_dir = get_special_folder (CSIDL_PERSONAL);
1970 #else
1971       data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1972
1973       if (data_dir && data_dir[0])
1974         data_dir = g_strdup (data_dir);
1975 #endif
1976       if (!data_dir || !data_dir[0])
1977         {
1978           g_get_any_init ();
1979
1980           if (g_home_dir)
1981             data_dir = g_build_filename (g_home_dir, ".local", 
1982                                          "share", NULL);
1983           else
1984             data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local", 
1985                                          "share", NULL);
1986         }
1987
1988       g_user_data_dir = data_dir;
1989     }
1990   else
1991     data_dir = g_user_data_dir;
1992
1993   G_UNLOCK (g_utils_global);
1994
1995   return data_dir;
1996 }
1997
1998 /**
1999  * g_get_user_config_dir:
2000  * 
2001  * Returns a base directory in which to store user-specific application 
2002  * configuration information such as user preferences and settings. 
2003  *
2004  * On UNIX platforms this is determined using the mechanisms described in
2005  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2006  * XDG Base Directory Specification</ulink>
2007  * 
2008  * Return value: a string owned by GLib that must not be modified 
2009  *               or freed.
2010  * Since: 2.6
2011  **/
2012 G_CONST_RETURN gchar*
2013 g_get_user_config_dir (void)
2014 {
2015   gchar *config_dir;  
2016
2017   G_LOCK (g_utils_global);
2018
2019   if (!g_user_config_dir)
2020     {
2021 #ifdef G_OS_WIN32
2022       config_dir = get_special_folder (CSIDL_APPDATA);
2023 #else
2024       config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2025
2026       if (config_dir && config_dir[0])
2027         config_dir = g_strdup (config_dir);
2028 #endif
2029       if (!config_dir || !config_dir[0])
2030         {
2031           g_get_any_init ();
2032
2033           if (g_home_dir)
2034             config_dir = g_build_filename (g_home_dir, ".config", NULL);
2035           else
2036             config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2037         }
2038       g_user_config_dir = config_dir;
2039     }
2040   else
2041     config_dir = g_user_config_dir;
2042
2043   G_UNLOCK (g_utils_global);
2044
2045   return config_dir;
2046 }
2047
2048 /**
2049  * g_get_user_cache_dir:
2050  * 
2051  * Returns a base directory in which to store non-essential, cached
2052  * data specific to particular user.
2053  *
2054  * On UNIX platforms this is determined using the mechanisms described in
2055  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2056  * XDG Base Directory Specification</ulink>
2057  * 
2058  * Return value: a string owned by GLib that must not be modified 
2059  *               or freed.
2060  * Since: 2.6
2061  **/
2062 G_CONST_RETURN gchar*
2063 g_get_user_cache_dir (void)
2064 {
2065   gchar *cache_dir;  
2066
2067   G_LOCK (g_utils_global);
2068
2069   if (!g_user_cache_dir)
2070     {
2071 #ifdef G_OS_WIN32
2072       cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2073 #else
2074       cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2075
2076       if (cache_dir && cache_dir[0])
2077           cache_dir = g_strdup (cache_dir);
2078 #endif
2079       if (!cache_dir || !cache_dir[0])
2080         {
2081           g_get_any_init ();
2082         
2083           if (g_home_dir)
2084             cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2085           else
2086             cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2087         }
2088       g_user_cache_dir = cache_dir;
2089     }
2090   else
2091     cache_dir = g_user_cache_dir;
2092
2093   G_UNLOCK (g_utils_global);
2094
2095   return cache_dir;
2096 }
2097
2098 #ifdef G_OS_WIN32
2099
2100 #undef g_get_system_data_dirs
2101
2102 static HMODULE
2103 get_module_for_address (gconstpointer address)
2104 {
2105   /* Holds the g_utils_global lock */
2106
2107   static gboolean beenhere = FALSE;
2108   typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2109   static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2110   HMODULE hmodule;
2111
2112   if (!address)
2113     return NULL;
2114
2115   if (!beenhere)
2116     {
2117       p_GetModuleHandleExA =
2118         (t_GetModuleHandleExA) GetProcAddress (LoadLibrary ("kernel32.dll"),
2119                                                "GetModuleHandleExA");
2120       beenhere = TRUE;
2121     }
2122
2123   if (p_GetModuleHandleExA == NULL ||
2124       !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2125                                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2126                                 address, &hmodule))
2127     {
2128       MEMORY_BASIC_INFORMATION mbi;
2129       VirtualQuery (address, &mbi, sizeof (mbi));
2130       hmodule = (HMODULE) mbi.AllocationBase;
2131     }
2132
2133   return hmodule;
2134 }
2135
2136 static gchar *
2137 get_module_share_dir (gconstpointer address)
2138 {
2139   HMODULE hmodule;
2140   gchar *filename = NULL;
2141   gchar *p, *retval;
2142   wchar_t wfilename[MAX_PATH];
2143
2144   hmodule = get_module_for_address (address);
2145   if (hmodule == NULL)
2146     return NULL;
2147
2148   if (GetModuleFileNameW (hmodule, wfilename, G_N_ELEMENTS (wfilename)))
2149     filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
2150
2151   if (filename == NULL)
2152     return NULL;
2153
2154   if ((p = strrchr (filename, G_DIR_SEPARATOR)) != NULL)
2155     *p = '\0';
2156
2157   p = strrchr (filename, G_DIR_SEPARATOR);
2158   if (p && (g_ascii_strcasecmp (p + 1, "bin") == 0))
2159     *p = '\0';
2160
2161   retval = g_build_filename (filename, "share", NULL);
2162   g_free (filename);
2163
2164   return retval;
2165 }
2166
2167 G_CONST_RETURN gchar * G_CONST_RETURN *
2168 g_win32_get_system_data_dirs_for_module (gconstpointer address)
2169 {
2170   GArray *data_dirs;
2171   HMODULE hmodule;
2172   static GHashTable *per_module_data_dirs = NULL;
2173   gchar **retval;
2174   gchar *p;
2175       
2176   if (address)
2177     {
2178       G_LOCK (g_utils_global);
2179       hmodule = get_module_for_address (address);
2180       if (hmodule != NULL)
2181         {
2182           if (per_module_data_dirs == NULL)
2183             per_module_data_dirs = g_hash_table_new (NULL, NULL);
2184           else
2185             {
2186               retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2187               
2188               if (retval != NULL)
2189                 {
2190                   G_UNLOCK (g_utils_global);
2191                   return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2192                 }
2193             }
2194         }
2195     }
2196
2197   data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2198
2199   /* Documents and Settings\All Users\Application Data */
2200   p = get_special_folder (CSIDL_COMMON_APPDATA);
2201   if (p)
2202     g_array_append_val (data_dirs, p);
2203   
2204   /* Documents and Settings\All Users\Documents */
2205   p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2206   if (p)
2207     g_array_append_val (data_dirs, p);
2208         
2209   /* Using the above subfolders of Documents and Settings perhaps
2210    * makes sense from a Windows perspective.
2211    *
2212    * But looking at the actual use cases of this function in GTK+
2213    * and GNOME software, what we really want is the "share"
2214    * subdirectory of the installation directory for the package
2215    * our caller is a part of.
2216    *
2217    * The address parameter, if non-NULL, points to a function in the
2218    * calling module. Use that to determine that module's installation
2219    * folder, and use its "share" subfolder.
2220    *
2221    * Additionally, also use the "share" subfolder of the installation
2222    * locations of GLib and the .exe file being run.
2223    *
2224    * To guard against none of the above being what is really wanted,
2225    * callers of this function should have Win32-specific code to look
2226    * up their installation folder themselves, and handle a subfolder
2227    * "share" of it in the same way as the folders returned from this
2228    * function.
2229    */
2230
2231   p = get_module_share_dir (address);
2232   if (p)
2233     g_array_append_val (data_dirs, p);
2234     
2235   p = g_win32_get_package_installation_subdirectory (NULL, dll_name, "share");
2236   if (p)
2237     g_array_append_val (data_dirs, p);
2238   
2239   p = g_win32_get_package_installation_subdirectory (NULL, NULL, "share");
2240   if (p)
2241     g_array_append_val (data_dirs, p);
2242
2243   retval = (gchar **) g_array_free (data_dirs, FALSE);
2244
2245   if (address)
2246     {
2247       if (hmodule != NULL)
2248         g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2249       G_UNLOCK (g_utils_global);
2250     }
2251
2252   return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2253 }
2254
2255 #endif
2256
2257 /**
2258  * g_get_system_data_dirs:
2259  * 
2260  * Returns an ordered list of base directories in which to access 
2261  * system-wide application data.
2262  *
2263  * On UNIX platforms this is determined using the mechanisms described in
2264  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2265  * XDG Base Directory Specification</ulink>
2266  * 
2267  * On Windows the first elements in the list are the Application Data
2268  * and Documents folders for All Users. (These can be determined only
2269  * on Windows 2000 or later and are not present in the list on other
2270  * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2271  * CSIDL_COMMON_DOCUMENTS.
2272  *
2273  * Then follows the "share" subfolder in the installation folder for
2274  * the package containing the DLL that calls this function, if it can
2275  * be determined.
2276  * 
2277  * Finally the list contains the "share" subfolder in the installation
2278  * folder for GLib, and in the installation folder for the package the
2279  * application's .exe file belongs to.
2280  *
2281  * The installation folders above are determined by looking up the
2282  * folder where the module (DLL or EXE) in question is located. If the
2283  * folder's name is "bin", its parent is used, otherwise the folder
2284  * itself.
2285  *
2286  * Note that on Windows the returned list can vary depending on where
2287  * this function is called.
2288  *
2289  * Return value: a %NULL-terminated array of strings owned by GLib that must 
2290  *               not be modified or freed.
2291  * Since: 2.6
2292  **/
2293 G_CONST_RETURN gchar * G_CONST_RETURN * 
2294 g_get_system_data_dirs (void)
2295 {
2296   gchar **data_dir_vector;
2297
2298   G_LOCK (g_utils_global);
2299
2300   if (!g_system_data_dirs)
2301     {
2302 #ifdef G_OS_WIN32
2303       data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2304 #else
2305       gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2306
2307       if (!data_dirs || !data_dirs[0])
2308           data_dirs = "/usr/local/share/:/usr/share/";
2309
2310       data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2311 #endif
2312
2313       g_system_data_dirs = data_dir_vector;
2314     }
2315   else
2316     data_dir_vector = g_system_data_dirs;
2317
2318   G_UNLOCK (g_utils_global);
2319
2320   return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2321 }
2322
2323 /**
2324  * g_get_system_config_dirs:
2325  * 
2326  * Returns an ordered list of base directories in which to access 
2327  * system-wide configuration information.
2328  *
2329  * On UNIX platforms this is determined using the mechanisms described in
2330  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2331  * XDG Base Directory Specification</ulink>
2332  * 
2333  * Return value: a %NULL-terminated array of strings owned by GLib that must 
2334  *               not be modified or freed.
2335  * Since: 2.6
2336  **/
2337 G_CONST_RETURN gchar * G_CONST_RETURN *
2338 g_get_system_config_dirs (void)
2339 {
2340   gchar *conf_dirs, **conf_dir_vector;
2341
2342   G_LOCK (g_utils_global);
2343
2344   if (!g_system_config_dirs)
2345     {
2346 #ifdef G_OS_WIN32
2347       conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2348       if (conf_dirs)
2349         {
2350           conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2351           g_free (conf_dirs);
2352         }
2353       else
2354         {
2355           /* Return empty list */
2356           conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2357         }
2358 #else
2359       conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2360
2361       if (!conf_dirs || !conf_dirs[0])
2362           conf_dirs = "/etc/xdg";
2363
2364       conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2365 #endif
2366
2367       g_system_config_dirs = conf_dir_vector;
2368     }
2369   else
2370     conf_dir_vector = g_system_config_dirs;
2371   G_UNLOCK (g_utils_global);
2372
2373   return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2374 }
2375
2376 #ifndef G_OS_WIN32
2377
2378 static GHashTable *alias_table = NULL;
2379
2380 /* read an alias file for the locales */
2381 static void
2382 read_aliases (gchar *file)
2383 {
2384   FILE *fp;
2385   char buf[256];
2386   
2387   if (!alias_table)
2388     alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2389   fp = fopen (file,"r");
2390   if (!fp)
2391     return;
2392   while (fgets (buf, 256, fp))
2393     {
2394       char *p, *q;
2395
2396       g_strstrip (buf);
2397
2398       /* Line is a comment */
2399       if ((buf[0] == '#') || (buf[0] == '\0'))
2400         continue;
2401
2402       /* Reads first column */
2403       for (p = buf, q = NULL; *p; p++) {
2404         if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2405           *p = '\0';
2406           q = p+1;
2407           while ((*q == '\t') || (*q == ' ')) {
2408             q++;
2409           }
2410           break;
2411         }
2412       }
2413       /* The line only had one column */
2414       if (!q || *q == '\0')
2415         continue;
2416       
2417       /* Read second column */
2418       for (p = q; *p; p++) {
2419         if ((*p == '\t') || (*p == ' ')) {
2420           *p = '\0';
2421           break;
2422         }
2423       }
2424
2425       /* Add to alias table if necessary */
2426       if (!g_hash_table_lookup (alias_table, buf)) {
2427         g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2428       }
2429     }
2430   fclose (fp);
2431 }
2432
2433 #endif
2434
2435 static char *
2436 unalias_lang (char *lang)
2437 {
2438 #ifndef G_OS_WIN32
2439   char *p;
2440   int i;
2441
2442   if (!alias_table)
2443     read_aliases ("/usr/share/locale/locale.alias");
2444
2445   i = 0;
2446   while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2447     {
2448       lang = p;
2449       if (i++ == 30)
2450         {
2451           static gboolean said_before = FALSE;
2452           if (!said_before)
2453             g_warning ("Too many alias levels for a locale, "
2454                        "may indicate a loop");
2455           said_before = TRUE;
2456           return lang;
2457         }
2458     }
2459 #endif
2460   return lang;
2461 }
2462
2463 /* Mask for components of locale spec. The ordering here is from
2464  * least significant to most significant
2465  */
2466 enum
2467 {
2468   COMPONENT_CODESET =   1 << 0,
2469   COMPONENT_TERRITORY = 1 << 1,
2470   COMPONENT_MODIFIER =  1 << 2
2471 };
2472
2473 /* Break an X/Open style locale specification into components
2474  */
2475 static guint
2476 explode_locale (const gchar *locale,
2477                 gchar      **language, 
2478                 gchar      **territory, 
2479                 gchar      **codeset, 
2480                 gchar      **modifier)
2481 {
2482   const gchar *uscore_pos;
2483   const gchar *at_pos;
2484   const gchar *dot_pos;
2485
2486   guint mask = 0;
2487
2488   uscore_pos = strchr (locale, '_');
2489   dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2490   at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2491
2492   if (at_pos)
2493     {
2494       mask |= COMPONENT_MODIFIER;
2495       *modifier = g_strdup (at_pos);
2496     }
2497   else
2498     at_pos = locale + strlen (locale);
2499
2500   if (dot_pos)
2501     {
2502       mask |= COMPONENT_CODESET;
2503       *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2504     }
2505   else
2506     dot_pos = at_pos;
2507
2508   if (uscore_pos)
2509     {
2510       mask |= COMPONENT_TERRITORY;
2511       *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2512     }
2513   else
2514     uscore_pos = dot_pos;
2515
2516   *language = g_strndup (locale, uscore_pos - locale);
2517
2518   return mask;
2519 }
2520
2521 /*
2522  * Compute all interesting variants for a given locale name -
2523  * by stripping off different components of the value.
2524  *
2525  * For simplicity, we assume that the locale is in
2526  * X/Open format: language[_territory][.codeset][@modifier]
2527  *
2528  * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2529  *       as well. We could just copy the code from glibc wholesale
2530  *       but it is big, ugly, and complicated, so I'm reluctant
2531  *       to do so when this should handle 99% of the time...
2532  */
2533 GSList *
2534 _g_compute_locale_variants (const gchar *locale)
2535 {
2536   GSList *retval = NULL;
2537
2538   gchar *language = NULL;
2539   gchar *territory = NULL;
2540   gchar *codeset = NULL;
2541   gchar *modifier = NULL;
2542
2543   guint mask;
2544   guint i;
2545
2546   g_return_val_if_fail (locale != NULL, NULL);
2547
2548   mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2549
2550   /* Iterate through all possible combinations, from least attractive
2551    * to most attractive.
2552    */
2553   for (i = 0; i <= mask; i++)
2554     if ((i & ~mask) == 0)
2555       {
2556         gchar *val = g_strconcat (language,
2557                                   (i & COMPONENT_TERRITORY) ? territory : "",
2558                                   (i & COMPONENT_CODESET) ? codeset : "",
2559                                   (i & COMPONENT_MODIFIER) ? modifier : "",
2560                                   NULL);
2561         retval = g_slist_prepend (retval, val);
2562       }
2563
2564   g_free (language);
2565   if (mask & COMPONENT_CODESET)
2566     g_free (codeset);
2567   if (mask & COMPONENT_TERRITORY)
2568     g_free (territory);
2569   if (mask & COMPONENT_MODIFIER)
2570     g_free (modifier);
2571
2572   return retval;
2573 }
2574
2575 /* The following is (partly) taken from the gettext package.
2576    Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc.  */
2577
2578 static const gchar *
2579 guess_category_value (const gchar *category_name)
2580 {
2581   const gchar *retval;
2582
2583   /* The highest priority value is the `LANGUAGE' environment
2584      variable.  This is a GNU extension.  */
2585   retval = g_getenv ("LANGUAGE");
2586   if ((retval != NULL) && (retval[0] != '\0'))
2587     return retval;
2588
2589   /* `LANGUAGE' is not set.  So we have to proceed with the POSIX
2590      methods of looking to `LC_ALL', `LC_xxx', and `LANG'.  On some
2591      systems this can be done by the `setlocale' function itself.  */
2592
2593   /* Setting of LC_ALL overwrites all other.  */
2594   retval = g_getenv ("LC_ALL");  
2595   if ((retval != NULL) && (retval[0] != '\0'))
2596     return retval;
2597
2598   /* Next comes the name of the desired category.  */
2599   retval = g_getenv (category_name);
2600   if ((retval != NULL) && (retval[0] != '\0'))
2601     return retval;
2602
2603   /* Last possibility is the LANG environment variable.  */
2604   retval = g_getenv ("LANG");
2605   if ((retval != NULL) && (retval[0] != '\0'))
2606     return retval;
2607
2608 #ifdef G_PLATFORM_WIN32
2609   /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2610    * LANG, which we already did above. Oh well. The main point of
2611    * calling g_win32_getlocale() is to get the thread's locale as used
2612    * by Windows and the Microsoft C runtime (in the "English_United
2613    * States" format) translated into the Unixish format.
2614    */
2615   retval = g_win32_getlocale ();
2616   if ((retval != NULL) && (retval[0] != '\0'))
2617     return retval;
2618 #endif  
2619
2620   return NULL;
2621 }
2622
2623 typedef struct _GLanguageNamesCache GLanguageNamesCache;
2624
2625 struct _GLanguageNamesCache {
2626   gchar *languages;
2627   gchar **language_names;
2628 };
2629
2630 static void
2631 language_names_cache_free (gpointer data)
2632 {
2633   GLanguageNamesCache *cache = data;
2634   g_free (cache->languages);
2635   g_strfreev (cache->language_names);
2636   g_free (cache);
2637 }
2638
2639 /**
2640  * g_get_language_names:
2641  * 
2642  * Computes a list of applicable locale names, which can be used to 
2643  * e.g. construct locale-dependent filenames or search paths. The returned 
2644  * list is sorted from most desirable to least desirable and always contains 
2645  * the default locale "C".
2646  *
2647  * For example, if LANGUAGE=de:en_US, then the returned list is
2648  * "de", "en_US", "en", "C".
2649  *
2650  * This function consults the environment variables <envar>LANGUAGE</envar>, 
2651  * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar> 
2652  * to find the list of locales specified by the user.
2653  * 
2654  * Return value: a %NULL-terminated array of strings owned by GLib 
2655  *    that must not be modified or freed.
2656  *
2657  * Since: 2.6
2658  **/
2659 G_CONST_RETURN gchar * G_CONST_RETURN * 
2660 g_get_language_names (void)
2661 {
2662   static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
2663   GLanguageNamesCache *cache = g_static_private_get (&cache_private);
2664   const gchar *value;
2665
2666   if (!cache)
2667     {
2668       cache = g_new0 (GLanguageNamesCache, 1);
2669       g_static_private_set (&cache_private, cache, language_names_cache_free);
2670     }
2671
2672   value = guess_category_value ("LC_MESSAGES");
2673   if (!value)
2674     value = "C";
2675
2676   if (!(cache->languages && strcmp (cache->languages, value) == 0))
2677     {
2678       gchar **languages;
2679       gchar **alist, **a;
2680       GSList *list, *l;
2681       gint i;
2682
2683       g_free (cache->languages);
2684       g_strfreev (cache->language_names);
2685       cache->languages = g_strdup (value);
2686
2687       alist = g_strsplit (value, ":", 0);
2688       list = NULL;
2689       for (a = alist; *a; a++)
2690         {
2691           gchar *b = unalias_lang (*a);
2692           list = g_slist_concat (list, _g_compute_locale_variants (b));
2693         }
2694       g_strfreev (alist);
2695       list = g_slist_append (list, g_strdup ("C"));
2696
2697       cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
2698       for (l = list, i = 0; l; l = l->next, i++)
2699         languages[i] = l->data;
2700       languages[i] = NULL;
2701
2702       g_slist_free (list);
2703     }
2704
2705   return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
2706 }
2707
2708 /**
2709  * g_direct_hash:
2710  * @v: a #gpointer key
2711  *
2712  * Converts a gpointer to a hash value.
2713  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
2714  * when using pointers as keys in a #GHashTable.
2715  *
2716  * Returns: a hash value corresponding to the key.
2717  */
2718 guint
2719 g_direct_hash (gconstpointer v)
2720 {
2721   return GPOINTER_TO_UINT (v);
2722 }
2723
2724 /**
2725  * g_direct_equal:
2726  * @v1: a key.
2727  * @v2: a key to compare with @v1.
2728  *
2729  * Compares two #gpointer arguments and returns %TRUE if they are equal.
2730  * It can be passed to g_hash_table_new() as the @key_equal_func
2731  * parameter, when using pointers as keys in a #GHashTable.
2732  * 
2733  * Returns: %TRUE if the two keys match.
2734  */
2735 gboolean
2736 g_direct_equal (gconstpointer v1,
2737                 gconstpointer v2)
2738 {
2739   return v1 == v2;
2740 }
2741
2742 /**
2743  * g_int_equal:
2744  * @v1: a pointer to a #gint key.
2745  * @v2: a pointer to a #gint key to compare with @v1.
2746  *
2747  * Compares the two #gint values being pointed to and returns 
2748  * %TRUE if they are equal.
2749  * It can be passed to g_hash_table_new() as the @key_equal_func
2750  * parameter, when using pointers to integers as keys in a #GHashTable.
2751  * 
2752  * Returns: %TRUE if the two keys match.
2753  */
2754 gboolean
2755 g_int_equal (gconstpointer v1,
2756              gconstpointer v2)
2757 {
2758   return *((const gint*) v1) == *((const gint*) v2);
2759 }
2760
2761 /**
2762  * g_int_hash:
2763  * @v: a pointer to a #gint key
2764  *
2765  * Converts a pointer to a #gint to a hash value.
2766  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
2767  * when using pointers to integers values as keys in a #GHashTable.
2768  *
2769  * Returns: a hash value corresponding to the key.
2770  */
2771 guint
2772 g_int_hash (gconstpointer v)
2773 {
2774   return *(const gint*) v;
2775 }
2776
2777 /**
2778  * g_nullify_pointer:
2779  * @nullify_location: the memory address of the pointer.
2780  * 
2781  * Set the pointer at the specified location to %NULL.
2782  **/
2783 void
2784 g_nullify_pointer (gpointer *nullify_location)
2785 {
2786   g_return_if_fail (nullify_location != NULL);
2787
2788   *nullify_location = NULL;
2789 }
2790
2791 /**
2792  * g_get_codeset:
2793  * 
2794  * Get the codeset for the current locale.
2795  * 
2796  * Return value: a newly allocated string containing the name
2797  * of the codeset. This string must be freed with g_free().
2798  **/
2799 gchar *
2800 g_get_codeset (void)
2801 {
2802   const gchar *charset;
2803
2804   g_get_charset (&charset);
2805
2806   return g_strdup (charset);
2807 }
2808
2809 /* This is called from g_thread_init(). It's used to
2810  * initialize some static data in a threadsafe way.
2811  */
2812 void
2813 _g_utils_thread_init (void)
2814 {
2815   g_get_language_names ();
2816 }
2817
2818 #ifdef ENABLE_NLS
2819
2820 #include <libintl.h>
2821
2822 #ifdef G_OS_WIN32
2823
2824 /**
2825  * _glib_get_locale_dir:
2826  *
2827  * Return the path to the lib\locale subfolder of the GLib
2828  * installation folder. The path is in the system codepage. We have to
2829  * use system codepage as bindtextdomain() doesn't have a UTF-8
2830  * interface.
2831  */
2832 static const gchar *
2833 _glib_get_locale_dir (void)
2834 {
2835   gchar *dir, *cp_dir;
2836   gchar *retval = NULL;
2837
2838   dir = g_win32_get_package_installation_directory (GETTEXT_PACKAGE, dll_name);
2839   cp_dir = g_win32_locale_filename_from_utf8 (dir);
2840   g_free (dir);
2841
2842   if (cp_dir)
2843     {
2844       /* Don't use g_build_filename() on pathnames in the system
2845        * codepage. In CJK locales cp_dir might end with a double-byte
2846        * character whose trailing byte is a backslash.
2847        */
2848       retval = g_strconcat (cp_dir, "\\lib\\locale", NULL);
2849       g_free (cp_dir);
2850     }
2851
2852   if (retval)
2853     return retval;
2854   else
2855     return g_strdup ("");
2856 }
2857
2858 #undef GLIB_LOCALE_DIR
2859 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
2860
2861 #endif /* G_OS_WIN32 */
2862
2863 G_CONST_RETURN gchar *
2864 _glib_gettext (const gchar *str)
2865 {
2866   static gboolean _glib_gettext_initialized = FALSE;
2867
2868   if (!_glib_gettext_initialized)
2869     {
2870       bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
2871 #    ifdef HAVE_BIND_TEXTDOMAIN_CODESET
2872       bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
2873 #    endif
2874       _glib_gettext_initialized = TRUE;
2875     }
2876   
2877   return dgettext (GETTEXT_PACKAGE, str);
2878 }
2879
2880 #endif /* ENABLE_NLS */
2881
2882 #ifdef G_OS_WIN32
2883
2884 /* Binary compatibility versions. Not for newly compiled code. */
2885
2886 #undef g_find_program_in_path
2887
2888 gchar*
2889 g_find_program_in_path (const gchar *program)
2890 {
2891   gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
2892   gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
2893   gchar *retval;
2894
2895   g_free (utf8_program);
2896   if (utf8_retval == NULL)
2897     return NULL;
2898   retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
2899   g_free (utf8_retval);
2900
2901   return retval;
2902 }
2903
2904 #undef g_get_current_dir
2905
2906 gchar*
2907 g_get_current_dir (void)
2908 {
2909   gchar *utf8_dir = g_get_current_dir_utf8 ();
2910   gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
2911   g_free (utf8_dir);
2912   return dir;
2913 }
2914
2915 #undef g_getenv
2916
2917 G_CONST_RETURN gchar*
2918 g_getenv (const gchar *variable)
2919 {
2920   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2921   const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
2922   gchar *value;
2923   GQuark quark;
2924
2925   g_free (utf8_variable);
2926   if (!utf8_value)
2927     return NULL;
2928   value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
2929   quark = g_quark_from_string (value);
2930   g_free (value);
2931
2932   return g_quark_to_string (quark);
2933 }
2934
2935 #undef g_setenv
2936
2937 gboolean
2938 g_setenv (const gchar *variable, 
2939           const gchar *value, 
2940           gboolean     overwrite)
2941 {
2942   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2943   gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
2944   gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
2945
2946   g_free (utf8_variable);
2947   g_free (utf8_value);
2948
2949   return retval;
2950 }
2951
2952 #undef g_unsetenv
2953
2954 void
2955 g_unsetenv (const gchar *variable)
2956 {
2957   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2958
2959   g_unsetenv_utf8 (utf8_variable);
2960
2961   g_free (utf8_variable);
2962 }
2963
2964 #undef g_get_user_name
2965
2966 G_CONST_RETURN gchar*
2967 g_get_user_name (void)
2968 {
2969   g_get_any_init_locked ();
2970   return g_user_name_cp;
2971 }
2972
2973 #undef g_get_real_name
2974
2975 G_CONST_RETURN gchar*
2976 g_get_real_name (void)
2977 {
2978   g_get_any_init_locked ();
2979   return g_real_name_cp;
2980 }
2981
2982 #undef g_get_home_dir
2983
2984 G_CONST_RETURN gchar*
2985 g_get_home_dir (void)
2986 {
2987   g_get_any_init_locked ();
2988   return g_home_dir_cp;
2989 }
2990
2991 #undef g_get_tmp_dir
2992
2993 G_CONST_RETURN gchar*
2994 g_get_tmp_dir (void)
2995 {
2996   g_get_any_init_locked ();
2997   return g_tmp_dir_cp;
2998 }
2999
3000 #endif
3001
3002 #define __G_UTILS_C__
3003 #include "galiasdef.c"