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