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