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