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