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