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