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