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