include cleanup
[platform/upstream/glib.git] / glib / gutils.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1998  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 /* 
28  * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
29  */
30
31 #include "config.h"
32
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #include <stdarg.h>
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <locale.h>
40 #include <string.h>
41 #include <ctype.h>              /* For tolower() */
42 #include <errno.h>
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #ifdef HAVE_PWD_H
46 #include <pwd.h>
47 #endif
48 #include <sys/types.h>
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
51 #endif
52 #ifdef HAVE_CRT_EXTERNS_H 
53 #include <crt_externs.h> /* for _NSGetEnviron */
54 #endif
55
56 /* implement gutils's inline functions
57  */
58 #define G_IMPLEMENT_INLINES 1
59 #define __G_UTILS_C__
60 #include "gutils.h"
61
62 #include "glib-init.h"
63 #include "genviron.h"
64 #include "gfileutils.h"
65 #include "ggettext.h"
66 #include "ghash.h"
67 #include "gthread.h"
68 #include "gtestutils.h"
69 #include "gunicode.h"
70 #include "gstrfuncs.h"
71 #include "garray.h"
72 #include "glibintl.h"
73
74 #ifdef G_PLATFORM_WIN32
75 #include "gconvert.h"
76 #include "gwin32.h"
77 #endif
78
79
80 /**
81  * SECTION:misc_utils
82  * @title: Miscellaneous Utility Functions
83  * @short_description: a selection of portable utility functions
84  *
85  * These are portable utility functions.
86  */
87
88 #ifdef G_PLATFORM_WIN32
89 #  include <windows.h>
90 #  ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
91 #    define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
92 #    define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
93 #  endif
94 #  include <lmcons.h>           /* For UNLEN */
95 #endif /* G_PLATFORM_WIN32 */
96
97 #ifdef G_OS_WIN32
98 #  include <direct.h>
99 #  include <shlobj.h>
100    /* older SDK (e.g. msvc 5.0) does not have these*/
101 #  ifndef CSIDL_MYMUSIC
102 #    define CSIDL_MYMUSIC 13
103 #  endif
104 #  ifndef CSIDL_MYVIDEO
105 #    define CSIDL_MYVIDEO 14
106 #  endif
107 #  ifndef CSIDL_INTERNET_CACHE
108 #    define CSIDL_INTERNET_CACHE 32
109 #  endif
110 #  ifndef CSIDL_COMMON_APPDATA
111 #    define CSIDL_COMMON_APPDATA 35
112 #  endif
113 #  ifndef CSIDL_MYPICTURES
114 #    define CSIDL_MYPICTURES 0x27
115 #  endif
116 #  ifndef CSIDL_COMMON_DOCUMENTS
117 #    define CSIDL_COMMON_DOCUMENTS 46
118 #  endif
119 #  ifndef CSIDL_PROFILE
120 #    define CSIDL_PROFILE 40
121 #  endif
122 #  include <process.h>
123 #endif
124
125 #ifdef HAVE_CARBON
126 #include <CoreServices/CoreServices.h>
127 #endif
128
129 #ifdef HAVE_CODESET
130 #include <langinfo.h>
131 #endif
132
133 #ifdef G_PLATFORM_WIN32
134
135 gchar *
136 _glib_get_dll_directory (void)
137 {
138   gchar *retval;
139   gchar *p;
140   wchar_t wc_fn[MAX_PATH];
141
142 #ifdef DLL_EXPORT
143   if (glib_dll == NULL)
144     return NULL;
145 #endif
146
147   /* This code is different from that in
148    * g_win32_get_package_installation_directory_of_module() in that
149    * here we return the actual folder where the GLib DLL is. We don't
150    * do the check for it being in a "bin" or "lib" subfolder and then
151    * returning the parent of that.
152    *
153    * In a statically built GLib, glib_dll will be NULL and we will
154    * thus look up the application's .exe file's location.
155    */
156   if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
157     return NULL;
158
159   retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
160
161   p = strrchr (retval, G_DIR_SEPARATOR);
162   if (p == NULL)
163     {
164       /* Wtf? */
165       return NULL;
166     }
167   *p = '\0';
168
169   return retval;
170 }
171
172 #endif
173
174 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
175 /**
176  * g_memmove: 
177  * @dest: the destination address to copy the bytes to.
178  * @src: the source address to copy the bytes from.
179  * @len: the number of bytes to copy.
180  *
181  * Copies a block of memory @len bytes long, from @src to @dest.
182  * The source and destination areas may overlap.
183  *
184  * In order to use this function, you must include 
185  * <filename>string.h</filename> yourself, because this macro will 
186  * typically simply resolve to memmove() and GLib does not include 
187  * <filename>string.h</filename> for you.
188  */
189 void 
190 g_memmove (gpointer      dest, 
191            gconstpointer src, 
192            gulong        len)
193 {
194   gchar* destptr = dest;
195   const gchar* srcptr = src;
196   if (src + len < dest || dest + len < src)
197     {
198       bcopy (src, dest, len);
199       return;
200     }
201   else if (dest <= src)
202     {
203       while (len--)
204         *(destptr++) = *(srcptr++);
205     }
206   else
207     {
208       destptr += len;
209       srcptr += len;
210       while (len--)
211         *(--destptr) = *(--srcptr);
212     }
213 }
214 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
215
216 #ifdef G_OS_WIN32
217 #undef g_atexit
218 #endif
219
220 /**
221  * g_atexit:
222  * @func: (scope async): the function to call on normal program termination.
223  * 
224  * Specifies a function to be called at normal program termination.
225  *
226  * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
227  * macro that maps to a call to the atexit() function in the C
228  * library. This means that in case the code that calls g_atexit(),
229  * i.e. atexit(), is in a DLL, the function will be called when the
230  * DLL is detached from the program. This typically makes more sense
231  * than that the function is called when the GLib DLL is detached,
232  * which happened earlier when g_atexit() was a function in the GLib
233  * DLL.
234  *
235  * The behaviour of atexit() in the context of dynamically loaded
236  * modules is not formally specified and varies wildly.
237  *
238  * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
239  * loaded module which is unloaded before the program terminates might
240  * well cause a crash at program exit.
241  *
242  * Some POSIX systems implement atexit() like Windows, and have each
243  * dynamically loaded module maintain an own atexit chain that is
244  * called when the module is unloaded.
245  *
246  * On other POSIX systems, before a dynamically loaded module is
247  * unloaded, the registered atexit functions (if any) residing in that
248  * module are called, regardless where the code that registered them
249  * resided. This is presumably the most robust approach.
250  *
251  * As can be seen from the above, for portability it's best to avoid
252  * calling g_atexit() (or atexit()) except in the main executable of a
253  * program.
254  */
255 void
256 g_atexit (GVoidFunc func)
257 {
258   gint result;
259   const gchar *error = NULL;
260
261   /* keep this in sync with glib.h */
262
263 #ifdef  G_NATIVE_ATEXIT
264   result = ATEXIT (func);
265   if (result)
266     error = g_strerror (errno);
267 #elif defined (HAVE_ATEXIT)
268 #  ifdef NeXT /* @#%@! NeXTStep */
269   result = !atexit ((void (*)(void)) func);
270   if (result)
271     error = g_strerror (errno);
272 #  else
273   result = atexit ((void (*)(void)) func);
274   if (result)
275     error = g_strerror (errno);
276 #  endif /* NeXT */
277 #elif defined (HAVE_ON_EXIT)
278   result = on_exit ((void (*)(int, void *)) func, NULL);
279   if (result)
280     error = g_strerror (errno);
281 #else
282   result = 0;
283   error = "no implementation";
284 #endif /* G_NATIVE_ATEXIT */
285
286   if (error)
287     g_error ("Could not register atexit() function: %s", error);
288 }
289
290 /* Based on execvp() from GNU Libc.
291  * Some of this code is cut-and-pasted into gspawn.c
292  */
293
294 static gchar*
295 my_strchrnul (const gchar *str, 
296               gchar        c)
297 {
298   gchar *p = (gchar*)str;
299   while (*p && (*p != c))
300     ++p;
301
302   return p;
303 }
304
305 #ifdef G_OS_WIN32
306
307 static gchar *inner_find_program_in_path (const gchar *program);
308
309 gchar*
310 g_find_program_in_path (const gchar *program)
311 {
312   const gchar *last_dot = strrchr (program, '.');
313
314   if (last_dot == NULL ||
315       strchr (last_dot, '\\') != NULL ||
316       strchr (last_dot, '/') != NULL)
317     {
318       const gint program_length = strlen (program);
319       gchar *pathext = g_build_path (";",
320                                      ".exe;.cmd;.bat;.com",
321                                      g_getenv ("PATHEXT"),
322                                      NULL);
323       gchar *p;
324       gchar *decorated_program;
325       gchar *retval;
326
327       p = pathext;
328       do
329         {
330           gchar *q = my_strchrnul (p, ';');
331
332           decorated_program = g_malloc (program_length + (q-p) + 1);
333           memcpy (decorated_program, program, program_length);
334           memcpy (decorated_program+program_length, p, q-p);
335           decorated_program [program_length + (q-p)] = '\0';
336           
337           retval = inner_find_program_in_path (decorated_program);
338           g_free (decorated_program);
339
340           if (retval != NULL)
341             {
342               g_free (pathext);
343               return retval;
344             }
345           p = q;
346         } while (*p++ != '\0');
347       g_free (pathext);
348       return NULL;
349     }
350   else
351     return inner_find_program_in_path (program);
352 }
353
354 #endif
355
356 /**
357  * g_find_program_in_path:
358  * @program: a program name in the GLib file name encoding
359  * 
360  * Locates the first executable named @program in the user's path, in the
361  * same way that execvp() would locate it. Returns an allocated string
362  * with the absolute path name, or %NULL if the program is not found in
363  * the path. If @program is already an absolute path, returns a copy of
364  * @program if @program exists and is executable, and %NULL otherwise.
365  *  
366  * On Windows, if @program does not have a file type suffix, tries
367  * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
368  * the <envar>PATHEXT</envar> environment variable. 
369  * 
370  * On Windows, it looks for the file in the same way as CreateProcess() 
371  * would. This means first in the directory where the executing
372  * program was loaded from, then in the current directory, then in the
373  * Windows 32-bit system directory, then in the Windows directory, and
374  * finally in the directories in the <envar>PATH</envar> environment 
375  * variable. If the program is found, the return value contains the 
376  * full name including the type suffix.
377  *
378  * Return value: absolute path, or %NULL
379  **/
380 #ifdef G_OS_WIN32
381 static gchar *
382 inner_find_program_in_path (const gchar *program)
383 #else
384 gchar*
385 g_find_program_in_path (const gchar *program)
386 #endif
387 {
388   const gchar *path, *p;
389   gchar *name, *freeme;
390 #ifdef G_OS_WIN32
391   const gchar *path_copy;
392   gchar *filename = NULL, *appdir = NULL;
393   gchar *sysdir = NULL, *windir = NULL;
394   int n;
395   wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
396     wwindir[MAXPATHLEN];
397 #endif
398   gsize len;
399   gsize pathlen;
400
401   g_return_val_if_fail (program != NULL, NULL);
402
403   /* If it is an absolute path, or a relative path including subdirectories,
404    * don't look in PATH.
405    */
406   if (g_path_is_absolute (program)
407       || strchr (program, G_DIR_SEPARATOR) != NULL
408 #ifdef G_OS_WIN32
409       || strchr (program, '/') != NULL
410 #endif
411       )
412     {
413       if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
414           !g_file_test (program, G_FILE_TEST_IS_DIR))
415         return g_strdup (program);
416       else
417         return NULL;
418     }
419   
420   path = g_getenv ("PATH");
421 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
422   if (path == NULL)
423     {
424       /* There is no `PATH' in the environment.  The default
425        * search path in GNU libc is the current directory followed by
426        * the path `confstr' returns for `_CS_PATH'.
427        */
428       
429       /* In GLib we put . last, for security, and don't use the
430        * unportable confstr(); UNIX98 does not actually specify
431        * what to search if PATH is unset. POSIX may, dunno.
432        */
433       
434       path = "/bin:/usr/bin:.";
435     }
436 #else
437   n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
438   if (n > 0 && n < MAXPATHLEN)
439     filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
440   
441   n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
442   if (n > 0 && n < MAXPATHLEN)
443     sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
444   
445   n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
446   if (n > 0 && n < MAXPATHLEN)
447     windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
448   
449   if (filename)
450     {
451       appdir = g_path_get_dirname (filename);
452       g_free (filename);
453     }
454   
455   path = g_strdup (path);
456
457   if (windir)
458     {
459       const gchar *tem = path;
460       path = g_strconcat (windir, ";", path, NULL);
461       g_free ((gchar *) tem);
462       g_free (windir);
463     }
464   
465   if (sysdir)
466     {
467       const gchar *tem = path;
468       path = g_strconcat (sysdir, ";", path, NULL);
469       g_free ((gchar *) tem);
470       g_free (sysdir);
471     }
472   
473   {
474     const gchar *tem = path;
475     path = g_strconcat (".;", path, NULL);
476     g_free ((gchar *) tem);
477   }
478   
479   if (appdir)
480     {
481       const gchar *tem = path;
482       path = g_strconcat (appdir, ";", path, NULL);
483       g_free ((gchar *) tem);
484       g_free (appdir);
485     }
486
487   path_copy = path;
488 #endif
489   
490   len = strlen (program) + 1;
491   pathlen = strlen (path);
492   freeme = name = g_malloc (pathlen + len + 1);
493   
494   /* Copy the file name at the top, including '\0'  */
495   memcpy (name + pathlen + 1, program, len);
496   name = name + pathlen;
497   /* And add the slash before the filename  */
498   *name = G_DIR_SEPARATOR;
499   
500   p = path;
501   do
502     {
503       char *startp;
504
505       path = p;
506       p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
507
508       if (p == path)
509         /* Two adjacent colons, or a colon at the beginning or the end
510          * of `PATH' means to search the current directory.
511          */
512         startp = name + 1;
513       else
514         startp = memcpy (name - (p - path), path, p - path);
515
516       if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
517           !g_file_test (startp, G_FILE_TEST_IS_DIR))
518         {
519           gchar *ret;
520           ret = g_strdup (startp);
521           g_free (freeme);
522 #ifdef G_OS_WIN32
523           g_free ((gchar *) path_copy);
524 #endif
525           return ret;
526         }
527     }
528   while (*p++ != '\0');
529   
530   g_free (freeme);
531 #ifdef G_OS_WIN32
532   g_free ((gchar *) path_copy);
533 #endif
534
535   return NULL;
536 }
537
538 /**
539  * g_bit_nth_lsf:
540  * @mask: a #gulong containing flags
541  * @nth_bit: the index of the bit to start the search from
542  *
543  * Find the position of the first bit set in @mask, searching
544  * from (but not including) @nth_bit upwards. Bits are numbered
545  * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
546  * usually). To start searching from the 0th bit, set @nth_bit to -1.
547  *
548  * Returns: the index of the first bit set which is higher than @nth_bit
549  */
550
551 /**
552  * g_bit_nth_msf:
553  * @mask: a #gulong containing flags
554  * @nth_bit: the index of the bit to start the search from
555  *
556  * Find the position of the first bit set in @mask, searching
557  * from (but not including) @nth_bit downwards. Bits are numbered
558  * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
559  * usually). To start searching from the last bit, set @nth_bit to
560  * -1 or GLIB_SIZEOF_LONG * 8.
561  *
562  * Returns: the index of the first bit set which is lower than @nth_bit
563  */
564
565 /**
566  * g_bit_storage:
567  * @number: a #guint
568  *
569  * Gets the number of bits used to hold @number,
570  * e.g. if @number is 4, 3 bits are needed.
571  *
572  * Returns: the number of bits used to hold @number
573  */
574
575 G_LOCK_DEFINE_STATIC (g_utils_global);
576
577 static  gchar   *g_tmp_dir = NULL;
578 static  gchar   *g_user_name = NULL;
579 static  gchar   *g_real_name = NULL;
580 static  gchar   *g_home_dir = NULL;
581 static  gchar   *g_host_name = NULL;
582
583 #ifdef G_OS_WIN32
584 /* System codepage versions of the above, kept at file level so that they,
585  * too, are produced only once.
586  */
587 static  gchar   *g_tmp_dir_cp = NULL;
588 static  gchar   *g_user_name_cp = NULL;
589 static  gchar   *g_real_name_cp = NULL;
590 static  gchar   *g_home_dir_cp = NULL;
591 #endif
592
593 static  gchar   *g_user_data_dir = NULL;
594 static  gchar  **g_system_data_dirs = NULL;
595 static  gchar   *g_user_cache_dir = NULL;
596 static  gchar   *g_user_config_dir = NULL;
597 static  gchar  **g_system_config_dirs = NULL;
598
599 static  gchar  **g_user_special_dirs = NULL;
600
601 /* fifteen minutes of fame for everybody */
602 #define G_USER_DIRS_EXPIRE      15 * 60
603
604 #ifdef G_OS_WIN32
605
606 static gchar *
607 get_special_folder (int csidl)
608 {
609   wchar_t path[MAX_PATH+1];
610   HRESULT hr;
611   LPITEMIDLIST pidl = NULL;
612   BOOL b;
613   gchar *retval = NULL;
614
615   hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
616   if (hr == S_OK)
617     {
618       b = SHGetPathFromIDListW (pidl, path);
619       if (b)
620         retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
621       CoTaskMemFree (pidl);
622     }
623   return retval;
624 }
625
626 static char *
627 get_windows_directory_root (void)
628 {
629   wchar_t wwindowsdir[MAX_PATH];
630
631   if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
632     {
633       /* Usually X:\Windows, but in terminal server environments
634        * might be an UNC path, AFAIK.
635        */
636       char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
637       char *p;
638
639       if (windowsdir == NULL)
640         return g_strdup ("C:\\");
641
642       p = (char *) g_path_skip_root (windowsdir);
643       if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
644         p--;
645       *p = '\0';
646       return windowsdir;
647     }
648   else
649     return g_strdup ("C:\\");
650 }
651
652 #endif
653
654 /* HOLDS: g_utils_global_lock */
655 static void
656 g_get_any_init_do (void)
657 {
658   gchar hostname[100];
659
660   g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
661   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
662     g_tmp_dir = g_strdup (g_getenv ("TMP"));
663   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
664     g_tmp_dir = g_strdup (g_getenv ("TEMP"));
665
666 #ifdef G_OS_WIN32
667   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
668     g_tmp_dir = get_windows_directory_root ();
669 #else  
670 #ifdef P_tmpdir
671   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
672     {
673       gsize k;    
674       g_tmp_dir = g_strdup (P_tmpdir);
675       k = strlen (g_tmp_dir);
676       if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
677         g_tmp_dir[k - 1] = '\0';
678     }
679 #endif
680   
681   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
682     {
683       g_tmp_dir = g_strdup ("/tmp");
684     }
685 #endif  /* !G_OS_WIN32 */
686   
687 #ifdef G_OS_WIN32
688   /* We check $HOME first for Win32, though it is a last resort for Unix
689    * where we prefer the results of getpwuid().
690    */
691   g_home_dir = g_strdup (g_getenv ("HOME"));
692
693   /* Only believe HOME if it is an absolute path and exists */
694   if (g_home_dir)
695     {
696       if (!(g_path_is_absolute (g_home_dir) &&
697             g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
698         {
699           g_free (g_home_dir);
700           g_home_dir = NULL;
701         }
702     }
703   
704   /* In case HOME is Unix-style (it happens), convert it to
705    * Windows style.
706    */
707   if (g_home_dir)
708     {
709       gchar *p;
710       while ((p = strchr (g_home_dir, '/')) != NULL)
711         *p = '\\';
712     }
713
714   if (!g_home_dir)
715     {
716       /* USERPROFILE is probably the closest equivalent to $HOME? */
717       if (g_getenv ("USERPROFILE") != NULL)
718         g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
719     }
720
721   if (!g_home_dir)
722     g_home_dir = get_special_folder (CSIDL_PROFILE);
723   
724   if (!g_home_dir)
725     g_home_dir = get_windows_directory_root ();
726 #endif /* G_OS_WIN32 */
727   
728 #ifdef HAVE_PWD_H
729   {
730     struct passwd *pw = NULL;
731     gpointer buffer = NULL;
732     gint error;
733     gchar *logname;
734
735 #  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
736     struct passwd pwd;
737 #    ifdef _SC_GETPW_R_SIZE_MAX  
738     /* This reurns the maximum length */
739     glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
740     
741     if (bufsize < 0)
742       bufsize = 64;
743 #    else /* _SC_GETPW_R_SIZE_MAX */
744     glong bufsize = 64;
745 #    endif /* _SC_GETPW_R_SIZE_MAX */
746
747     logname = (gchar *) g_getenv ("LOGNAME");
748         
749     do
750       {
751         g_free (buffer);
752         /* we allocate 6 extra bytes to work around a bug in 
753          * Mac OS < 10.3. See #156446
754          */
755         buffer = g_malloc (bufsize + 6);
756         errno = 0;
757         
758 #    ifdef HAVE_POSIX_GETPWUID_R
759         if (logname) {
760           error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
761           if (!pw || (pw->pw_uid != getuid ())) {
762             /* LOGNAME is lying, fall back to looking up the uid */
763             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
764           }
765         } else {
766           error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
767         }
768         error = error < 0 ? errno : error;
769 #    else /* HAVE_NONPOSIX_GETPWUID_R */
770    /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
771 #      if defined(_AIX) || defined(__hpux)
772         error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
773         pw = error == 0 ? &pwd : NULL;
774 #      else /* !_AIX */
775         if (logname) {
776           pw = getpwnam_r (logname, &pwd, buffer, bufsize);
777           if (!pw || (pw->pw_uid != getuid ())) {
778             /* LOGNAME is lying, fall back to looking up the uid */
779             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
780           }
781         } else {
782           pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
783         }
784         error = pw ? 0 : errno;
785 #      endif /* !_AIX */            
786 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
787         
788         if (!pw)
789           {
790             /* we bail out prematurely if the user id can't be found
791              * (should be pretty rare case actually), or if the buffer
792              * should be sufficiently big and lookups are still not
793              * successful.
794              */
795             if (error == 0 || error == ENOENT)
796               {
797                 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
798                            (gulong) getuid ());
799                 break;
800               }
801             if (bufsize > 32 * 1024)
802               {
803                 g_warning ("getpwuid_r(): failed due to: %s.",
804                            g_strerror (error));
805                 break;
806               }
807             
808             bufsize *= 2;
809           }
810       }
811     while (!pw);
812 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
813     
814     if (!pw)
815       {
816         setpwent ();
817         pw = getpwuid (getuid ());
818         endpwent ();
819       }
820     if (pw)
821       {
822         g_user_name = g_strdup (pw->pw_name);
823
824         if (pw->pw_gecos && *pw->pw_gecos != '\0') 
825           {
826             gchar **gecos_fields;
827             gchar **name_parts;
828
829             /* split the gecos field and substitute '&' */
830             gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
831             name_parts = g_strsplit (gecos_fields[0], "&", 0);
832             pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
833             g_real_name = g_strjoinv (pw->pw_name, name_parts);
834             g_strfreev (gecos_fields);
835             g_strfreev (name_parts);
836           }
837
838         if (!g_home_dir)
839           g_home_dir = g_strdup (pw->pw_dir);
840       }
841     g_free (buffer);
842   }
843   
844 #else /* !HAVE_PWD_H */
845   
846 #ifdef G_OS_WIN32
847   {
848     guint len = UNLEN+1;
849     wchar_t buffer[UNLEN+1];
850     
851     if (GetUserNameW (buffer, (LPDWORD) &len))
852       {
853         g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
854         g_real_name = g_strdup (g_user_name);
855       }
856   }
857 #endif /* G_OS_WIN32 */
858
859 #endif /* !HAVE_PWD_H */
860
861 #ifndef G_OS_WIN32
862   if (!g_home_dir)
863     g_home_dir = g_strdup (g_getenv ("HOME"));
864 #endif
865
866 #ifdef __EMX__
867   /* change '\\' in %HOME% to '/' */
868   g_strdelimit (g_home_dir, "\\",'/');
869 #endif
870   if (!g_user_name)
871     g_user_name = g_strdup ("somebody");
872   if (!g_real_name)
873     g_real_name = g_strdup ("Unknown");
874
875   {
876 #ifndef G_OS_WIN32
877     gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
878 #else
879     DWORD size = sizeof (hostname);
880     gboolean hostname_fail = (!GetComputerName (hostname, &size));
881 #endif
882     g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
883   }
884
885 #ifdef G_OS_WIN32
886   g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
887   g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
888   g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
889
890   if (!g_tmp_dir_cp)
891     g_tmp_dir_cp = g_strdup ("\\");
892   if (!g_user_name_cp)
893     g_user_name_cp = g_strdup ("somebody");
894   if (!g_real_name_cp)
895     g_real_name_cp = g_strdup ("Unknown");
896
897   /* home_dir might be NULL, unlike tmp_dir, user_name and
898    * real_name.
899    */
900   if (g_home_dir)
901     g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
902   else
903     g_home_dir_cp = NULL;
904 #endif /* G_OS_WIN32 */
905 }
906
907 static inline void
908 g_get_any_init (void)
909 {
910   if (!g_tmp_dir)
911     g_get_any_init_do ();
912 }
913
914 static inline void
915 g_get_any_init_locked (void)
916 {
917   G_LOCK (g_utils_global);
918   g_get_any_init ();
919   G_UNLOCK (g_utils_global);
920 }
921
922
923 /**
924  * g_get_user_name:
925  *
926  * Gets the user name of the current user. The encoding of the returned
927  * string is system-defined. On UNIX, it might be the preferred file name
928  * encoding, or something else, and there is no guarantee that it is even
929  * consistent on a machine. On Windows, it is always UTF-8.
930  *
931  * Returns: the user name of the current user.
932  */
933 const gchar *
934 g_get_user_name (void)
935 {
936   g_get_any_init_locked ();
937   return g_user_name;
938 }
939
940 /**
941  * g_get_real_name:
942  *
943  * Gets the real name of the user. This usually comes from the user's entry 
944  * in the <filename>passwd</filename> file. The encoding of the returned 
945  * string is system-defined. (On Windows, it is, however, always UTF-8.) 
946  * If the real user name cannot be determined, the string "Unknown" is 
947  * returned.
948  *
949  * Returns: the user's real name.
950  */
951 const gchar *
952 g_get_real_name (void)
953 {
954   g_get_any_init_locked ();
955   return g_real_name;
956 }
957
958 /**
959  * g_get_home_dir:
960  *
961  * Gets the current user's home directory as defined in the 
962  * password database.
963  *
964  * Note that in contrast to traditional UNIX tools, this function 
965  * prefers <filename>passwd</filename> entries over the <envar>HOME</envar> 
966  * environment variable. 
967  *
968  * One of the reasons for this decision is that applications in many 
969  * cases need special handling to deal with the case where 
970  * <envar>HOME</envar> is
971  * <simplelist>
972  *   <member>Not owned by the user</member>
973  *   <member>Not writeable</member>
974  *   <member>Not even readable</member>
975  * </simplelist>
976  * Since applications are in general <emphasis>not</emphasis> written 
977  * to deal with these situations it was considered better to make 
978  * g_get_home_dir() not pay attention to <envar>HOME</envar> and to 
979  * return the real home directory for the user. If applications
980  * want to pay attention to <envar>HOME</envar>, they can do:
981  * |[
982  *  const char *homedir = g_getenv ("HOME");
983  *   if (!homedir)
984  *      homedir = g_get_home_dir (<!-- -->);
985  * ]|
986  *
987  * Returns: the current user's home directory
988  */
989 const gchar *
990 g_get_home_dir (void)
991 {
992   g_get_any_init_locked ();
993   return g_home_dir;
994 }
995
996 /**
997  * g_get_tmp_dir:
998  *
999  * Gets the directory to use for temporary files. This is found from 
1000  * inspecting the environment variables <envar>TMPDIR</envar>, 
1001  * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none 
1002  * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows. 
1003  * The encoding of the returned string is system-defined. On Windows, 
1004  * it is always UTF-8. The return value is never %NULL or the empty string.
1005  *
1006  * Returns: the directory to use for temporary files.
1007  */
1008 const gchar *
1009 g_get_tmp_dir (void)
1010 {
1011   g_get_any_init_locked ();
1012   return g_tmp_dir;
1013 }
1014
1015 /**
1016  * g_get_host_name:
1017  *
1018  * Return a name for the machine. 
1019  *
1020  * The returned name is not necessarily a fully-qualified domain name,
1021  * or even present in DNS or some other name service at all. It need
1022  * not even be unique on your local network or site, but usually it
1023  * is. Callers should not rely on the return value having any specific
1024  * properties like uniqueness for security purposes. Even if the name
1025  * of the machine is changed while an application is running, the
1026  * return value from this function does not change. The returned
1027  * string is owned by GLib and should not be modified or freed. If no
1028  * name can be determined, a default fixed string "localhost" is
1029  * returned.
1030  *
1031  * Returns: the host name of the machine.
1032  *
1033  * Since: 2.8
1034  */
1035 const gchar *
1036 g_get_host_name (void)
1037 {
1038   g_get_any_init_locked ();
1039   return g_host_name;
1040 }
1041
1042 G_LOCK_DEFINE_STATIC (g_prgname);
1043 static gchar *g_prgname = NULL;
1044
1045 /**
1046  * g_get_prgname:
1047  *
1048  * Gets the name of the program. This name should <emphasis>not</emphasis> 
1049  * be localized, contrast with g_get_application_name().
1050  * (If you are using GDK or GTK+ the program name is set in gdk_init(), 
1051  * which is called by gtk_init(). The program name is found by taking 
1052  * the last component of <literal>argv[0]</literal>.)
1053  *
1054  * Returns: the name of the program. The returned string belongs 
1055  * to GLib and must not be modified or freed.
1056  */
1057 gchar*
1058 g_get_prgname (void)
1059 {
1060   gchar* retval;
1061
1062   G_LOCK (g_prgname);
1063 #ifdef G_OS_WIN32
1064   if (g_prgname == NULL)
1065     {
1066       static gboolean beenhere = FALSE;
1067
1068       if (!beenhere)
1069         {
1070           gchar *utf8_buf = NULL;
1071           wchar_t buf[MAX_PATH+1];
1072
1073           beenhere = TRUE;
1074           if (GetModuleFileNameW (GetModuleHandle (NULL),
1075                                   buf, G_N_ELEMENTS (buf)) > 0)
1076             utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1077
1078           if (utf8_buf)
1079             {
1080               g_prgname = g_path_get_basename (utf8_buf);
1081               g_free (utf8_buf);
1082             }
1083         }
1084     }
1085 #endif
1086   retval = g_prgname;
1087   G_UNLOCK (g_prgname);
1088
1089   return retval;
1090 }
1091
1092 /**
1093  * g_set_prgname:
1094  * @prgname: the name of the program.
1095  *
1096  * Sets the name of the program. This name should <emphasis>not</emphasis> 
1097  * be localized, contrast with g_set_application_name(). Note that for 
1098  * thread-safety reasons this function can only be called once.
1099  */
1100 void
1101 g_set_prgname (const gchar *prgname)
1102 {
1103   G_LOCK (g_prgname);
1104   g_free (g_prgname);
1105   g_prgname = g_strdup (prgname);
1106   G_UNLOCK (g_prgname);
1107 }
1108
1109 G_LOCK_DEFINE_STATIC (g_application_name);
1110 static gchar *g_application_name = NULL;
1111
1112 /**
1113  * g_get_application_name:
1114  * 
1115  * Gets a human-readable name for the application, as set by
1116  * g_set_application_name(). This name should be localized if
1117  * possible, and is intended for display to the user.  Contrast with
1118  * g_get_prgname(), which gets a non-localized name. If
1119  * g_set_application_name() has not been called, returns the result of
1120  * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1121  * been called).
1122  * 
1123  * Return value: human-readable application name. may return %NULL
1124  *
1125  * Since: 2.2
1126  **/
1127 const gchar *
1128 g_get_application_name (void)
1129 {
1130   gchar* retval;
1131
1132   G_LOCK (g_application_name);
1133   retval = g_application_name;
1134   G_UNLOCK (g_application_name);
1135
1136   if (retval == NULL)
1137     return g_get_prgname ();
1138   
1139   return retval;
1140 }
1141
1142 /**
1143  * g_set_application_name:
1144  * @application_name: localized name of the application
1145  *
1146  * Sets a human-readable name for the application. This name should be
1147  * localized if possible, and is intended for display to the user.
1148  * Contrast with g_set_prgname(), which sets a non-localized name.
1149  * g_set_prgname() will be called automatically by gtk_init(),
1150  * but g_set_application_name() will not.
1151  *
1152  * Note that for thread safety reasons, this function can only
1153  * be called once.
1154  *
1155  * The application name will be used in contexts such as error messages,
1156  * or when displaying an application's name in the task list.
1157  * 
1158  * Since: 2.2
1159  **/
1160 void
1161 g_set_application_name (const gchar *application_name)
1162 {
1163   gboolean already_set = FALSE;
1164         
1165   G_LOCK (g_application_name);
1166   if (g_application_name)
1167     already_set = TRUE;
1168   else
1169     g_application_name = g_strdup (application_name);
1170   G_UNLOCK (g_application_name);
1171
1172   if (already_set)
1173     g_warning ("g_set_application_name() called multiple times");
1174 }
1175
1176 /**
1177  * g_get_user_data_dir:
1178  * 
1179  * Returns a base directory in which to access application data such
1180  * as icons that is customized for a particular user.  
1181  *
1182  * On UNIX platforms this is determined using the mechanisms described in
1183  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1184  * XDG Base Directory Specification</ulink>.
1185  * In this case the directory retrieved will be XDG_DATA_HOME.
1186  *
1187  * On Windows this is the folder to use for local (as opposed to
1188  * roaming) application data. See documentation for
1189  * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1190  * what g_get_user_config_dir() returns.
1191  *
1192  * Return value: a string owned by GLib that must not be modified 
1193  *               or freed.
1194  * Since: 2.6
1195  **/
1196 const gchar *
1197 g_get_user_data_dir (void)
1198 {
1199   gchar *data_dir;  
1200
1201   G_LOCK (g_utils_global);
1202
1203   if (!g_user_data_dir)
1204     {
1205 #ifdef G_OS_WIN32
1206       data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1207 #else
1208       data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1209
1210       if (data_dir && data_dir[0])
1211         data_dir = g_strdup (data_dir);
1212 #endif
1213       if (!data_dir || !data_dir[0])
1214         {
1215           g_get_any_init ();
1216
1217           if (g_home_dir)
1218             data_dir = g_build_filename (g_home_dir, ".local", 
1219                                          "share", NULL);
1220           else
1221             data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local", 
1222                                          "share", NULL);
1223         }
1224
1225       g_user_data_dir = data_dir;
1226     }
1227   else
1228     data_dir = g_user_data_dir;
1229
1230   G_UNLOCK (g_utils_global);
1231
1232   return data_dir;
1233 }
1234
1235 static void
1236 g_init_user_config_dir (void)
1237 {
1238   gchar *config_dir;
1239
1240   if (!g_user_config_dir)
1241     {
1242 #ifdef G_OS_WIN32
1243       config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1244 #else
1245       config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1246
1247       if (config_dir && config_dir[0])
1248         config_dir = g_strdup (config_dir);
1249 #endif
1250       if (!config_dir || !config_dir[0])
1251         {
1252           g_get_any_init ();
1253
1254           if (g_home_dir)
1255             config_dir = g_build_filename (g_home_dir, ".config", NULL);
1256           else
1257             config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
1258         }
1259
1260       g_user_config_dir = config_dir;
1261     }
1262 }
1263
1264 /**
1265  * g_get_user_config_dir:
1266  * 
1267  * Returns a base directory in which to store user-specific application 
1268  * configuration information such as user preferences and settings. 
1269  *
1270  * On UNIX platforms this is determined using the mechanisms described in
1271  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1272  * XDG Base Directory Specification</ulink>.
1273  * In this case the directory retrieved will be XDG_CONFIG_HOME.
1274  *
1275  * On Windows this is the folder to use for local (as opposed to
1276  * roaming) application data. See documentation for
1277  * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1278  * what g_get_user_data_dir() returns.
1279  *
1280  * Return value: a string owned by GLib that must not be modified 
1281  *               or freed.
1282  * Since: 2.6
1283  **/
1284 const gchar *
1285 g_get_user_config_dir (void)
1286 {
1287   G_LOCK (g_utils_global);
1288
1289   g_init_user_config_dir ();
1290
1291   G_UNLOCK (g_utils_global);
1292
1293   return g_user_config_dir;
1294 }
1295
1296 /**
1297  * g_get_user_cache_dir:
1298  * 
1299  * Returns a base directory in which to store non-essential, cached
1300  * data specific to particular user.
1301  *
1302  * On UNIX platforms this is determined using the mechanisms described in
1303  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1304  * XDG Base Directory Specification</ulink>.
1305  * In this case the directory retrieved will be XDG_CACHE_HOME.
1306  *
1307  * On Windows is the directory that serves as a common repository for
1308  * temporary Internet files. A typical path is
1309  * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1310  * See documentation for CSIDL_INTERNET_CACHE.
1311  *
1312  * Return value: a string owned by GLib that must not be modified 
1313  *               or freed.
1314  * Since: 2.6
1315  **/
1316 const gchar *
1317 g_get_user_cache_dir (void)
1318 {
1319   gchar *cache_dir;  
1320
1321   G_LOCK (g_utils_global);
1322
1323   if (!g_user_cache_dir)
1324     {
1325 #ifdef G_OS_WIN32
1326       cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1327 #else
1328       cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1329
1330       if (cache_dir && cache_dir[0])
1331           cache_dir = g_strdup (cache_dir);
1332 #endif
1333       if (!cache_dir || !cache_dir[0])
1334         {
1335           g_get_any_init ();
1336         
1337           if (g_home_dir)
1338             cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
1339           else
1340             cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
1341         }
1342       g_user_cache_dir = cache_dir;
1343     }
1344   else
1345     cache_dir = g_user_cache_dir;
1346
1347   G_UNLOCK (g_utils_global);
1348
1349   return cache_dir;
1350 }
1351
1352 /**
1353  * g_get_user_runtime_dir:
1354  *
1355  * Returns a directory that is unique to the current user on the local
1356  * system.
1357  *
1358  * On UNIX platforms this is determined using the mechanisms described in
1359  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1360  * XDG Base Directory Specification</ulink>.  This is the directory
1361  * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
1362  * In the case that this variable is not set, GLib will issue a warning
1363  * message to stderr and return the value of g_get_user_cache_dir().
1364  *
1365  * On Windows this is the folder to use for local (as opposed to
1366  * roaming) application data. See documentation for
1367  * CSIDL_LOCAL_APPDATA.  Note that on Windows it thus is the same as
1368  * what g_get_user_config_dir() returns.
1369  *
1370  * Returns: a string owned by GLib that must not be modified or freed.
1371  *
1372  * Since: 2.28
1373  **/
1374 const gchar *
1375 g_get_user_runtime_dir (void)
1376 {
1377 #ifndef G_OS_WIN32
1378   static const gchar *runtime_dir;
1379   static gsize initialised;
1380
1381   if (g_once_init_enter (&initialised))
1382     {
1383       runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1384       
1385       g_once_init_leave (&initialised, 1);
1386     }
1387
1388   if (runtime_dir)
1389     return runtime_dir;
1390
1391   /* Both fallback for UNIX and the default
1392    * in Windows: use the user cache directory.
1393    */
1394 #endif
1395
1396   return g_get_user_cache_dir ();
1397 }
1398
1399 #ifdef HAVE_CARBON
1400
1401 static gchar *
1402 find_folder (OSType type)
1403 {
1404   gchar *filename = NULL;
1405   FSRef  found;
1406
1407   if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1408     {
1409       CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1410
1411       if (url)
1412         {
1413           CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1414
1415           if (path)
1416             {
1417               filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1418
1419               if (! filename)
1420                 {
1421                   filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1422
1423                   CFStringGetCString (path, filename,
1424                                       CFStringGetLength (path) * 3 + 1,
1425                                       kCFStringEncodingUTF8);
1426                 }
1427
1428               CFRelease (path);
1429             }
1430
1431           CFRelease (url);
1432         }
1433     }
1434
1435   return filename;
1436 }
1437
1438 static void
1439 load_user_special_dirs (void)
1440 {
1441   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1442   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1443   g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1444   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1445   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1446   g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1447   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1448   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1449 }
1450
1451 #endif /* HAVE_CARBON */
1452
1453 #if defined(G_OS_WIN32)
1454 static void
1455 load_user_special_dirs (void)
1456 {
1457   typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1458                                                     DWORD dwFlags,
1459                                                     HANDLE hToken,
1460                                                     PWSTR *ppszPath);
1461   t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1462
1463   static const GUID FOLDERID_Downloads =
1464     { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1465   static const GUID FOLDERID_Public =
1466     { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1467
1468   wchar_t *wcp;
1469
1470   p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1471                                                                     "SHGetKnownFolderPath");
1472
1473   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1474   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1475
1476   if (p_SHGetKnownFolderPath == NULL)
1477     {
1478       g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1479     }
1480   else
1481     {
1482       wcp = NULL;
1483       (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1484       if (wcp)
1485         {
1486           g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1487           if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1488               g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1489           CoTaskMemFree (wcp);
1490         }
1491       else
1492           g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1493     }
1494
1495   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1496   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1497
1498   if (p_SHGetKnownFolderPath == NULL)
1499     {
1500       /* XXX */
1501       g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1502     }
1503   else
1504     {
1505       wcp = NULL;
1506       (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1507       if (wcp)
1508         {
1509           g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1510           if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1511               g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1512           CoTaskMemFree (wcp);
1513         }
1514       else
1515           g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1516     }
1517   
1518   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1519   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1520 }
1521 #endif /* G_OS_WIN32 */
1522
1523 static void g_init_user_config_dir (void);
1524
1525 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
1526
1527 /* adapted from xdg-user-dir-lookup.c
1528  *
1529  * Copyright (C) 2007 Red Hat Inc.
1530  *
1531  * Permission is hereby granted, free of charge, to any person
1532  * obtaining a copy of this software and associated documentation files
1533  * (the "Software"), to deal in the Software without restriction,
1534  * including without limitation the rights to use, copy, modify, merge,
1535  * publish, distribute, sublicense, and/or sell copies of the Software,
1536  * and to permit persons to whom the Software is furnished to do so,
1537  * subject to the following conditions: 
1538  *
1539  * The above copyright notice and this permission notice shall be
1540  * included in all copies or substantial portions of the Software. 
1541  *
1542  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1543  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1544  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1545  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1546  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1547  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1548  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1549  * SOFTWARE.
1550  */
1551 static void
1552 load_user_special_dirs (void)
1553 {
1554   gchar *config_file;
1555   gchar *data;
1556   gchar **lines;
1557   gint n_lines, i;
1558   
1559   g_init_user_config_dir ();
1560   config_file = g_build_filename (g_user_config_dir,
1561                                   "user-dirs.dirs",
1562                                   NULL);
1563   
1564   if (!g_file_get_contents (config_file, &data, NULL, NULL))
1565     {
1566       g_free (config_file);
1567       return;
1568     }
1569
1570   lines = g_strsplit (data, "\n", -1);
1571   n_lines = g_strv_length (lines);
1572   g_free (data);
1573   
1574   for (i = 0; i < n_lines; i++)
1575     {
1576       gchar *buffer = lines[i];
1577       gchar *d, *p;
1578       gint len;
1579       gboolean is_relative = FALSE;
1580       GUserDirectory directory;
1581
1582       /* Remove newline at end */
1583       len = strlen (buffer);
1584       if (len > 0 && buffer[len - 1] == '\n')
1585         buffer[len - 1] = 0;
1586       
1587       p = buffer;
1588       while (*p == ' ' || *p == '\t')
1589         p++;
1590       
1591       if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1592         {
1593           directory = G_USER_DIRECTORY_DESKTOP;
1594           p += strlen ("XDG_DESKTOP_DIR");
1595         }
1596       else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1597         {
1598           directory = G_USER_DIRECTORY_DOCUMENTS;
1599           p += strlen ("XDG_DOCUMENTS_DIR");
1600         }
1601       else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1602         {
1603           directory = G_USER_DIRECTORY_DOWNLOAD;
1604           p += strlen ("XDG_DOWNLOAD_DIR");
1605         }
1606       else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1607         {
1608           directory = G_USER_DIRECTORY_MUSIC;
1609           p += strlen ("XDG_MUSIC_DIR");
1610         }
1611       else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1612         {
1613           directory = G_USER_DIRECTORY_PICTURES;
1614           p += strlen ("XDG_PICTURES_DIR");
1615         }
1616       else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1617         {
1618           directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1619           p += strlen ("XDG_PUBLICSHARE_DIR");
1620         }
1621       else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1622         {
1623           directory = G_USER_DIRECTORY_TEMPLATES;
1624           p += strlen ("XDG_TEMPLATES_DIR");
1625         }
1626       else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1627         {
1628           directory = G_USER_DIRECTORY_VIDEOS;
1629           p += strlen ("XDG_VIDEOS_DIR");
1630         }
1631       else
1632         continue;
1633
1634       while (*p == ' ' || *p == '\t')
1635         p++;
1636
1637       if (*p != '=')
1638         continue;
1639       p++;
1640
1641       while (*p == ' ' || *p == '\t')
1642         p++;
1643
1644       if (*p != '"')
1645         continue;
1646       p++;
1647
1648       if (strncmp (p, "$HOME", 5) == 0)
1649         {
1650           p += 5;
1651           is_relative = TRUE;
1652         }
1653       else if (*p != '/')
1654         continue;
1655
1656       d = strrchr (p, '"');
1657       if (!d)
1658         continue;
1659       *d = 0;
1660
1661       d = p;
1662       
1663       /* remove trailing slashes */
1664       len = strlen (d);
1665       if (d[len - 1] == '/')
1666         d[len - 1] = 0;
1667       
1668       if (is_relative)
1669         {
1670           g_get_any_init ();
1671           g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
1672         }
1673       else
1674         g_user_special_dirs[directory] = g_strdup (d);
1675     }
1676
1677   g_strfreev (lines);
1678   g_free (config_file);
1679 }
1680
1681 #endif /* G_OS_UNIX && !HAVE_CARBON */
1682
1683
1684 /**
1685  * g_reload_user_special_dirs_cache:
1686  *
1687  * Resets the cache used for g_get_user_special_dir(), so
1688  * that the latest on-disk version is used. Call this only
1689  * if you just changed the data on disk yourself.
1690  *
1691  * Due to threadsafety issues this may cause leaking of strings
1692  * that were previously returned from g_get_user_special_dir()
1693  * that can't be freed. We ensure to only leak the data for
1694  * the directories that actually changed value though.
1695  *
1696  * Since: 2.22
1697  */
1698 void
1699 g_reload_user_special_dirs_cache (void)
1700 {
1701   int i;
1702
1703   G_LOCK (g_utils_global);
1704
1705   if (g_user_special_dirs != NULL)
1706     {
1707       /* save a copy of the pointer, to check if some memory can be preserved */
1708       char **old_g_user_special_dirs = g_user_special_dirs;
1709       char *old_val;
1710
1711       /* recreate and reload our cache */
1712       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1713       load_user_special_dirs ();
1714
1715       /* only leak changed directories */
1716       for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1717         {
1718           old_val = old_g_user_special_dirs[i];
1719           if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1720             {
1721               /* don't leak */
1722               g_free (g_user_special_dirs[i]);
1723               g_user_special_dirs[i] = old_val;
1724             }
1725           else
1726             g_free (old_val);
1727         }
1728
1729       /* free the old array */
1730       g_free (old_g_user_special_dirs);
1731     }
1732
1733   G_UNLOCK (g_utils_global);
1734 }
1735
1736 /**
1737  * g_get_user_special_dir:
1738  * @directory: the logical id of special directory
1739  *
1740  * Returns the full path of a special directory using its logical id.
1741  *
1742  * On Unix this is done using the XDG special user directories.
1743  * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1744  * falls back to <filename>$HOME/Desktop</filename> when XDG special
1745  * user directories have not been set up. 
1746  *
1747  * Depending on the platform, the user might be able to change the path
1748  * of the special directory without requiring the session to restart; GLib
1749  * will not reflect any change once the special directories are loaded.
1750  *
1751  * Return value: the path to the specified special directory, or %NULL
1752  *   if the logical id was not found. The returned string is owned by
1753  *   GLib and should not be modified or freed.
1754  *
1755  * Since: 2.14
1756  */
1757 const gchar *
1758 g_get_user_special_dir (GUserDirectory directory)
1759 {
1760   g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1761                         directory < G_USER_N_DIRECTORIES, NULL);
1762
1763   G_LOCK (g_utils_global);
1764
1765   if (G_UNLIKELY (g_user_special_dirs == NULL))
1766     {
1767       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1768
1769       load_user_special_dirs ();
1770
1771       /* Special-case desktop for historical compatibility */
1772       if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1773         {
1774           g_get_any_init ();
1775
1776           g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
1777             g_build_filename (g_home_dir, "Desktop", NULL);
1778         }
1779     }
1780
1781   G_UNLOCK (g_utils_global);
1782
1783   return g_user_special_dirs[directory];
1784 }
1785
1786 #ifdef G_OS_WIN32
1787
1788 #undef g_get_system_data_dirs
1789
1790 static HMODULE
1791 get_module_for_address (gconstpointer address)
1792 {
1793   /* Holds the g_utils_global lock */
1794
1795   static gboolean beenhere = FALSE;
1796   typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1797   static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1798   HMODULE hmodule = NULL;
1799
1800   if (!address)
1801     return NULL;
1802
1803   if (!beenhere)
1804     {
1805       p_GetModuleHandleExA =
1806         (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1807                                                "GetModuleHandleExA");
1808       beenhere = TRUE;
1809     }
1810
1811   if (p_GetModuleHandleExA == NULL ||
1812       !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1813                                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1814                                 address, &hmodule))
1815     {
1816       MEMORY_BASIC_INFORMATION mbi;
1817       VirtualQuery (address, &mbi, sizeof (mbi));
1818       hmodule = (HMODULE) mbi.AllocationBase;
1819     }
1820
1821   return hmodule;
1822 }
1823
1824 static gchar *
1825 get_module_share_dir (gconstpointer address)
1826 {
1827   HMODULE hmodule;
1828   gchar *filename;
1829   gchar *retval;
1830
1831   hmodule = get_module_for_address (address);
1832   if (hmodule == NULL)
1833     return NULL;
1834
1835   filename = g_win32_get_package_installation_directory_of_module (hmodule);
1836   retval = g_build_filename (filename, "share", NULL);
1837   g_free (filename);
1838
1839   return retval;
1840 }
1841
1842 const gchar * const *
1843 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
1844 {
1845   GArray *data_dirs;
1846   HMODULE hmodule;
1847   static GHashTable *per_module_data_dirs = NULL;
1848   gchar **retval;
1849   gchar *p;
1850   gchar *exe_root;
1851       
1852   if (address_of_function)
1853     {
1854       G_LOCK (g_utils_global);
1855       hmodule = get_module_for_address (address_of_function);
1856       if (hmodule != NULL)
1857         {
1858           if (per_module_data_dirs == NULL)
1859             per_module_data_dirs = g_hash_table_new (NULL, NULL);
1860           else
1861             {
1862               retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1863               
1864               if (retval != NULL)
1865                 {
1866                   G_UNLOCK (g_utils_global);
1867                   return (const gchar * const *) retval;
1868                 }
1869             }
1870         }
1871     }
1872
1873   data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1874
1875   /* Documents and Settings\All Users\Application Data */
1876   p = get_special_folder (CSIDL_COMMON_APPDATA);
1877   if (p)
1878     g_array_append_val (data_dirs, p);
1879   
1880   /* Documents and Settings\All Users\Documents */
1881   p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1882   if (p)
1883     g_array_append_val (data_dirs, p);
1884         
1885   /* Using the above subfolders of Documents and Settings perhaps
1886    * makes sense from a Windows perspective.
1887    *
1888    * But looking at the actual use cases of this function in GTK+
1889    * and GNOME software, what we really want is the "share"
1890    * subdirectory of the installation directory for the package
1891    * our caller is a part of.
1892    *
1893    * The address_of_function parameter, if non-NULL, points to a
1894    * function in the calling module. Use that to determine that
1895    * module's installation folder, and use its "share" subfolder.
1896    *
1897    * Additionally, also use the "share" subfolder of the installation
1898    * locations of GLib and the .exe file being run.
1899    *
1900    * To guard against none of the above being what is really wanted,
1901    * callers of this function should have Win32-specific code to look
1902    * up their installation folder themselves, and handle a subfolder
1903    * "share" of it in the same way as the folders returned from this
1904    * function.
1905    */
1906
1907   p = get_module_share_dir (address_of_function);
1908   if (p)
1909     g_array_append_val (data_dirs, p);
1910     
1911   if (glib_dll != NULL)
1912     {
1913       gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1914       p = g_build_filename (glib_root, "share", NULL);
1915       if (p)
1916         g_array_append_val (data_dirs, p);
1917       g_free (glib_root);
1918     }
1919   
1920   exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1921   p = g_build_filename (exe_root, "share", NULL);
1922   if (p)
1923     g_array_append_val (data_dirs, p);
1924   g_free (exe_root);
1925
1926   retval = (gchar **) g_array_free (data_dirs, FALSE);
1927
1928   if (address_of_function)
1929     {
1930       if (hmodule != NULL)
1931         g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1932       G_UNLOCK (g_utils_global);
1933     }
1934
1935   return (const gchar * const *) retval;
1936 }
1937
1938 #endif
1939
1940 /**
1941  * g_get_system_data_dirs:
1942  * 
1943  * Returns an ordered list of base directories in which to access 
1944  * system-wide application data.
1945  *
1946  * On UNIX platforms this is determined using the mechanisms described in
1947  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1948  * XDG Base Directory Specification</ulink>
1949  * In this case the list of directories retrieved will be XDG_DATA_DIRS.
1950  *
1951  * On Windows the first elements in the list are the Application Data
1952  * and Documents folders for All Users. (These can be determined only
1953  * on Windows 2000 or later and are not present in the list on other
1954  * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1955  * CSIDL_COMMON_DOCUMENTS.
1956  *
1957  * Then follows the "share" subfolder in the installation folder for
1958  * the package containing the DLL that calls this function, if it can
1959  * be determined.
1960  * 
1961  * Finally the list contains the "share" subfolder in the installation
1962  * folder for GLib, and in the installation folder for the package the
1963  * application's .exe file belongs to.
1964  *
1965  * The installation folders above are determined by looking up the
1966  * folder where the module (DLL or EXE) in question is located. If the
1967  * folder's name is "bin", its parent is used, otherwise the folder
1968  * itself.
1969  *
1970  * Note that on Windows the returned list can vary depending on where
1971  * this function is called.
1972  *
1973  * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must 
1974  *               not be modified or freed.
1975  * Since: 2.6
1976  **/
1977 const gchar * const * 
1978 g_get_system_data_dirs (void)
1979 {
1980   gchar **data_dir_vector;
1981
1982   G_LOCK (g_utils_global);
1983
1984   if (!g_system_data_dirs)
1985     {
1986 #ifdef G_OS_WIN32
1987       data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
1988 #else
1989       gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1990
1991       if (!data_dirs || !data_dirs[0])
1992           data_dirs = "/usr/local/share/:/usr/share/";
1993
1994       data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1995 #endif
1996
1997       g_system_data_dirs = data_dir_vector;
1998     }
1999   else
2000     data_dir_vector = g_system_data_dirs;
2001
2002   G_UNLOCK (g_utils_global);
2003
2004   return (const gchar * const *) data_dir_vector;
2005 }
2006
2007 /**
2008  * g_get_system_config_dirs:
2009  * 
2010  * Returns an ordered list of base directories in which to access 
2011  * system-wide configuration information.
2012  *
2013  * On UNIX platforms this is determined using the mechanisms described in
2014  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2015  * XDG Base Directory Specification</ulink>.
2016  * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2017  *
2018  * On Windows is the directory that contains application data for all users.
2019  * A typical path is C:\Documents and Settings\All Users\Application Data.
2020  * This folder is used for application data that is not user specific.
2021  * For example, an application can store a spell-check dictionary, a database
2022  * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2023  * This information will not roam and is available to anyone using the computer.
2024  *
2025  * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must 
2026  *               not be modified or freed.
2027  * Since: 2.6
2028  **/
2029 const gchar * const *
2030 g_get_system_config_dirs (void)
2031 {
2032   gchar *conf_dirs, **conf_dir_vector;
2033
2034   G_LOCK (g_utils_global);
2035
2036   if (!g_system_config_dirs)
2037     {
2038 #ifdef G_OS_WIN32
2039       conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2040       if (conf_dirs)
2041         {
2042           conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2043           g_free (conf_dirs);
2044         }
2045       else
2046         {
2047           /* Return empty list */
2048           conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2049         }
2050 #else
2051       conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2052
2053       if (!conf_dirs || !conf_dirs[0])
2054           conf_dirs = "/etc/xdg";
2055
2056       conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2057 #endif
2058
2059       g_system_config_dirs = conf_dir_vector;
2060     }
2061   else
2062     conf_dir_vector = g_system_config_dirs;
2063   G_UNLOCK (g_utils_global);
2064
2065   return (const gchar * const *) conf_dir_vector;
2066 }
2067
2068 /**
2069  * g_nullify_pointer:
2070  * @nullify_location: the memory address of the pointer.
2071  *
2072  * Set the pointer at the specified location to %NULL.
2073  **/
2074 void
2075 g_nullify_pointer (gpointer *nullify_location)
2076 {
2077   g_return_if_fail (nullify_location != NULL);
2078
2079   *nullify_location = NULL;
2080 }
2081
2082 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2083 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2084 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2085 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2086 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2087 #define EXABYTE_FACTOR  (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2088
2089 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2090 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2091 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2092 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2093 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2094 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2095
2096 /**
2097  * g_format_size:
2098  * @size: a size in bytes
2099  *
2100  * Formats a size (for example the size of a file) into a human readable
2101  * string.  Sizes are rounded to the nearest size prefix (kB, MB, GB)
2102  * and are displayed rounded to the nearest tenth. E.g. the file size
2103  * 3292528 bytes will be converted into the string "3.2 MB".
2104  *
2105  * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2106  *
2107  * This string should be freed with g_free() when not needed any longer.
2108  *
2109  * See g_format_size_full() for more options about how the size might be
2110  * formatted.
2111  *
2112  * Returns: a newly-allocated formatted string containing a human readable
2113  *     file size
2114  *
2115  * Since: 2.30
2116  */
2117 gchar *
2118 g_format_size (guint64 size)
2119 {
2120   return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2121 }
2122
2123 /**
2124  * GFormatSizeFlags:
2125  * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2126  * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2127  *     of the returned string.  For example, "45.6 kB (45,612 bytes)".
2128  * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2129  *     suffixes. IEC units should only be used for reporting things with
2130  *     a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2131  *     Network and storage sizes should be reported in the normal SI units.
2132  *
2133  * Flags to modify the format of the string returned by g_format_size_full().
2134  */
2135
2136 /**
2137  * g_format_size_full:
2138  * @size: a size in bytes
2139  * @flags: #GFormatSizeFlags to modify the output
2140  *
2141  * Formats a size.
2142  *
2143  * This function is similar to g_format_size() but allows for flags
2144  * that modify the output. See #GFormatSizeFlags.
2145  *
2146  * Returns: a newly-allocated formatted string containing a human
2147  *     readable file size
2148  *
2149  * Since: 2.30
2150  */
2151 gchar *
2152 g_format_size_full (guint64          size,
2153                     GFormatSizeFlags flags)
2154 {
2155   GString *string;
2156
2157   string = g_string_new (NULL);
2158
2159   if (flags & G_FORMAT_SIZE_IEC_UNITS)
2160     {
2161       if (size < KIBIBYTE_FACTOR)
2162         {
2163           g_string_printf (string,
2164                            g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2165                            (guint) size);
2166           flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2167         }
2168
2169       else if (size < MEBIBYTE_FACTOR)
2170         g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2171       else if (size < GIBIBYTE_FACTOR)
2172         g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2173
2174       else if (size < TEBIBYTE_FACTOR)
2175         g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2176
2177       else if (size < PEBIBYTE_FACTOR)
2178         g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2179
2180       else if (size < EXBIBYTE_FACTOR)
2181         g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2182
2183       else
2184         g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2185     }
2186   else
2187     {
2188       if (size < KILOBYTE_FACTOR)
2189         {
2190           g_string_printf (string,
2191                            g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2192                            (guint) size);
2193           flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2194         }
2195
2196       else if (size < MEGABYTE_FACTOR)
2197         g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2198
2199       else if (size < GIGABYTE_FACTOR)
2200         g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2201
2202       else if (size < TERABYTE_FACTOR)
2203         g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2204       else if (size < PETABYTE_FACTOR)
2205         g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2206
2207       else if (size < EXABYTE_FACTOR)
2208         g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2209
2210       else
2211         g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2212     }
2213
2214   if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2215     {
2216       /* First problem: we need to use the number of bytes to decide on
2217        * the plural form that is used for display, but the number of
2218        * bytes potentially exceeds the size of a guint (which is what
2219        * ngettext() takes).
2220        *
2221        * From a pragmatic standpoint, it seems that all known languages
2222        * base plural forms on one or both of the following:
2223        *
2224        *   - the lowest digits of the number
2225        *
2226        *   - if the number if greater than some small value
2227        *
2228        * Here's how we fake it:  Draw an arbitrary line at one thousand.
2229        * If the number is below that, then fine.  If it is above it,
2230        * then we take the modulus of the number by one thousand (in
2231        * order to keep the lowest digits) and add one thousand to that
2232        * (in order to ensure that 1001 is not treated the same as 1).
2233        */
2234       guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2235
2236       /* Second problem: we need to translate the string "%u byte" and
2237        * "%u bytes" for pluralisation, but the correct number format to
2238        * use for a gsize is different depending on which architecture
2239        * we're on.
2240        *
2241        * Solution: format the number separately and use "%s bytes" on
2242        * all platforms.
2243        */
2244       const gchar *translated_format;
2245       gchar *formatted_number;
2246
2247       /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2248       translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2249       /* XXX: Windows doesn't support the "'" format modifier, so we
2250        * must not use it there.  Instead, just display the number
2251        * without separation.  Bug #655336 is open until a solution is
2252        * found.
2253        */
2254 #ifndef G_OS_WIN32
2255       formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2256 #else
2257       formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2258 #endif
2259
2260       g_string_append (string, " (");
2261       g_string_append_printf (string, translated_format, formatted_number);
2262       g_free (formatted_number);
2263       g_string_append (string, ")");
2264     }
2265
2266   return g_string_free (string, FALSE);
2267 }
2268
2269 /**
2270  * g_format_size_for_display:
2271  * @size: a size in bytes
2272  *
2273  * Formats a size (for example the size of a file) into a human
2274  * readable string. Sizes are rounded to the nearest size prefix
2275  * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2276  * E.g. the file size 3292528 bytes will be converted into the
2277  * string "3.1 MB".
2278  *
2279  * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2280  *
2281  * This string should be freed with g_free() when not needed any longer.
2282  *
2283  * Returns: a newly-allocated formatted string containing a human
2284  *     readable file size
2285  *
2286  * Since: 2.16
2287  *
2288  * Deprecated:2.30: This function is broken due to its use of SI
2289  *     suffixes to denote IEC units. Use g_format_size() instead.
2290  */
2291 gchar *
2292 g_format_size_for_display (goffset size)
2293 {
2294   if (size < (goffset) KIBIBYTE_FACTOR)
2295     return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2296   else
2297     {
2298       gdouble displayed_size;
2299
2300       if (size < (goffset) MEBIBYTE_FACTOR)
2301         {
2302           displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2303           return g_strdup_printf (_("%.1f KB"), displayed_size);
2304         }
2305       else if (size < (goffset) GIBIBYTE_FACTOR)
2306         {
2307           displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2308           return g_strdup_printf (_("%.1f MB"), displayed_size);
2309         }
2310       else if (size < (goffset) TEBIBYTE_FACTOR)
2311         {
2312           displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2313           return g_strdup_printf (_("%.1f GB"), displayed_size);
2314         }
2315       else if (size < (goffset) PEBIBYTE_FACTOR)
2316         {
2317           displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2318           return g_strdup_printf (_("%.1f TB"), displayed_size);
2319         }
2320       else if (size < (goffset) EXBIBYTE_FACTOR)
2321         {
2322           displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2323           return g_strdup_printf (_("%.1f PB"), displayed_size);
2324         }
2325       else
2326         {
2327           displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2328           return g_strdup_printf (_("%.1f EB"), displayed_size);
2329         }
2330     }
2331 }
2332
2333 #ifdef G_OS_WIN32
2334
2335 /**
2336  * _glib_get_locale_dir:
2337  *
2338  * Return the path to the share\locale or lib\locale subfolder of the
2339  * GLib installation folder. The path is in the system codepage. We
2340  * have to use system codepage as bindtextdomain() doesn't have a
2341  * UTF-8 interface.
2342  */
2343 gchar *
2344 _glib_get_locale_dir (void)
2345 {
2346   gchar *install_dir = NULL, *locale_dir;
2347   gchar *retval = NULL;
2348
2349   if (glib_dll != NULL)
2350     install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
2351
2352   if (install_dir)
2353     {
2354       /*
2355        * Append "/share/locale" or "/lib/locale" depending on whether
2356        * autoconfigury detected GNU gettext or not.
2357        */
2358       const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
2359       while (*--p != '/')
2360         ;
2361       while (*--p != '/')
2362         ;
2363
2364       locale_dir = g_build_filename (install_dir, p, NULL);
2365
2366       retval = g_win32_locale_filename_from_utf8 (locale_dir);
2367
2368       g_free (install_dir);
2369       g_free (locale_dir);
2370     }
2371
2372   if (retval)
2373     return retval;
2374   else
2375     return g_strdup ("");
2376 }
2377
2378 #undef GLIB_LOCALE_DIR
2379
2380 #endif /* G_OS_WIN32 */
2381
2382
2383 #if defined (G_OS_WIN32) && !defined (_WIN64)
2384
2385 /* Binary compatibility versions. Not for newly compiled code. */
2386
2387 #undef g_find_program_in_path
2388
2389 gchar*
2390 g_find_program_in_path (const gchar *program)
2391 {
2392   gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
2393   gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
2394   gchar *retval;
2395
2396   g_free (utf8_program);
2397   if (utf8_retval == NULL)
2398     return NULL;
2399   retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
2400   g_free (utf8_retval);
2401
2402   return retval;
2403 }
2404
2405 #undef g_get_user_name
2406
2407 const gchar *
2408 g_get_user_name (void)
2409 {
2410   g_get_any_init_locked ();
2411   return g_user_name_cp;
2412 }
2413
2414 #undef g_get_real_name
2415
2416 const gchar *
2417 g_get_real_name (void)
2418 {
2419   g_get_any_init_locked ();
2420   return g_real_name_cp;
2421 }
2422
2423 #undef g_get_home_dir
2424
2425 const gchar *
2426 g_get_home_dir (void)
2427 {
2428   g_get_any_init_locked ();
2429   return g_home_dir_cp;
2430 }
2431
2432 #undef g_get_tmp_dir
2433
2434 const gchar *
2435 g_get_tmp_dir (void)
2436 {
2437   g_get_any_init_locked ();
2438   return g_tmp_dir_cp;
2439 }
2440
2441 #endif