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