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