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