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